Egg上手
框架內(nèi)置基礎(chǔ)對象
- this
*this對象比較特殊,分析應(yīng)為每次請求時和ctx一起實例化一個散劫,然后將app、ctx等掛在this之下 - Application
-
特點
- 繼承自Koa.application
- 全局應(yīng)用對象
- 一個應(yīng)用只會實例化一次
-
獲取
幾乎所有被框架 Loader 加載的文件(Controller商叹,Service穆趴,Schedule 等),都可以 export 一個函數(shù)窟却,這個函數(shù)會被 Loader 調(diào)用昼丑,并使用 app 作為參數(shù)
* > 框架內(nèi)置基礎(chǔ)對象
* 啟動自定義腳本
js // app.js module.exports = (app) => { app.cache = new Cache(); };
分析:這里函數(shù)在定義的時候就是直接時作為參數(shù)傳進(jìn)來的,所以直接使用即可
* Controller
* 直接使用
js // app/controller/user.js class UserController extends Controller { async fetch() { this.ctx.body = app.cache.get(this.ctx.query.id); } }
分析:經(jīng)過測試直接使用報錯夸赫,不贊成使用
* this.ctx.app
js // app/controller/user.js class UserController extends Controller { async fetch() { this.ctx.body = this.ctx.app.cache.get(this.ctx.query.id); } }
分析:經(jīng)過測試this.app===this.ctx.app為真
* 繼承于 Controller, Service 基類的實例
* this.app
js // app/controller/user.js class UserController extends Controller { async fetch() { this.ctx.body = this.app.cache.get(this.ctx.query.id); } };
建議使用
this.app或者this.ctx.app
,經(jīng)過測試this.app===this.ctx.app為真
-
- context
-
特點
Context 是一個請求級別的對象菩帝,繼承自 Koa.Context。在每一次收到用戶請求時,框架會實例化一個 Context 對象呼奢,這個對象封裝了這次用戶請求的信息宜雀,并提供了許多便捷的方法來獲取請求參數(shù)或者設(shè)置響應(yīng)信息∥沾。框架會將所有的 Service 掛載到 Context 實例上辐董,一些插件也會將一些其他的方法和對象掛載到它上面(egg-sequelize 會將所有的 model 掛載在 Context 上)
* 請求級別的對象
* 繼承自Koa.Context
* 每次請求時實例化
-
獲取
- 常規(guī)下掛在this下
- 特別的,在啟動自定義腳本是需要創(chuàng)建一個匿名 Context 實例
// app.js module.exports = app => { app.beforeStart(async () => { const ctx = app.createAnonymousContext(); // preload before app start await ctx.service.posts.load(); }); }
- 在定時任務(wù)中的每一個 task 都接受一個 Context 實例作為參數(shù)
// app/schedule/refresh.js exports.task = async ctx => { await ctx.service.posts.refresh(); };
-
其他模塊一般掛在this禀综、ctx或者app之下简烘。