VonaJS AOP編程:魔術方法
在VonaJS框架中,AOP編程包括三方面:控制器切面、內部切面和外部切面。內部切面包括兩個能力:AOP Method和魔術方法。這里我們簡要介紹一下魔術方法的用法。
魔術方法
魔術方法,允許我們在 Class 內部通過__get__和__set__切入動態屬性或方法
舉例:Module Scope
為了讓 IOC 容器的使用更加簡潔和直觀,VonaJS 推薦優先使用依賴查找策略,從而使用更少的裝飾器函數,使用更少的類型標注。通過Module Scope對象訪問模塊提供的資源,就是踐行依賴查找策略的機制之一
- 參見: 模塊Scope
比如,模塊 demo-student 中有一個 model student,用于 crud 操作。可以這樣使用 model:
import { ModelStudent } from '../model/student.ts';
async findMany(params) {
const model = this.bean._getBean(ModelStudent);
return await model.selectAndCount(params);
}
使用魔術方法:
async findMany(params) {
return await this.scope.model.student.selectAndCount(params);
}
this.scope.model.xxx: 通過魔術方法動態獲取當前模塊中的 model 實例
舉例:CRUD(魔術方法)
Vona ORM 采用魔術方法的機制進一步簡化操作數據的代碼
- 參見: CRUD(魔術方法)
比如,通過字段id查詢學生信息,代碼如下:
async findOne(id) {
return await this.scope.model.student.get({ id });
}
使用魔術方法:
async findOne(id) {
return await this.scope.model.student.getById(id);
}
- 系統自動從 method name
getById中解析出參數id,然后調用實際的 CRUD 方法,這里就是:get({ id })
創建Class
可以在任何 Class 中實現魔術方法。下面,以 Service 為例,在模塊 demo-student 中創建一個 Service color,代碼如下:
- 如何創建 Service,參見: Service
import { BeanBase } from 'vona';
import { Service } from 'vona-module-a-bean';
@Service()
export class ServiceColor extends BeanBase {}
__get__
然后,通過__get__實現顏色值的獲取
1. 添加代碼骨架
在 VSCode 編輯器中,輸入代碼片段aopmagicget,自動生成代碼骨架:
@Service()
export class ServiceColor extends BeanBase {
+ protected __get__(prop: string) {}
}
2. 實現自定義邏輯
@Service()
export class ServiceColor extends BeanBase {
+ private _colors = {
+ red: '#FF0000',
+ green: '#00FF00',
+ blue: '#0000FF',
+ };
protected __get__(prop: string) {
+ return this._colors[prop];
}
}
3. 添加類型合并
通過接口類型合并的機制為顏色提供類型定義
export interface ServiceColor {
red: string;
green: string;
blue: string;
}
4. 使用魔術方法
async test() {
console.log(this.scope.service.color.red);
console.log(this.scope.service.color.green);
console.log(this.scope.service.color.blue);
}
__set__
然后,通過__set__實現顏色值的設置
1. 添加代碼骨架
在 VSCode 編輯器中,輸入代碼片段aopmagicset,自動生成代碼骨架:
@Service()
export class ServiceColor extends BeanBase {
+ protected __set__(prop: string, value: any): boolean {
+ return false;
+ }
}
2. 實現自定義邏輯
@Service()
export class ServiceColor extends BeanBase {
private _colors = {
red: '#FF0000',
green: '#00FF00',
blue: '#0000FF',
+ black: '',
};
protected __set__(prop: string, value: any): boolean {
+ if (this._colors[prop] === undefined) return false;
+ this._colors[prop] = value;
+ return true;
}
}
- 如果為
prop設置了值,返回true,否則返回false
3. 添加類型合并
通過接口類型合并的機制為顏色提供類型定義
export interface ServiceColor {
red: string;
green: string;
blue: string;
+ black: string;
}
4. 使用魔術方法
async test() {
this.scope.service.color.black = '#000000';
console.log(this.scope.service.color.black);
}

在VonaJS框架中,AOP編程包括三方面:控制器切面、內部切面和外部切面。內部切面包括兩個能力:AOP Method和魔術方法。這里我們簡要介紹一下魔術方法的用法。
浙公網安備 33010602011771號