# 加载器-Loader [TOC] 在Controller,Model,Task中经常用到。 ## 自定义加载器 可以自定义加载器,需要实现ILoader接口,然后在AppServer的__construct方法中注入。 ```php /** * 可以在这里自定义Loader,但必须是ILoader接口 * AppServer constructor. */ public function __construct() { $this->setLoader(new Loader()); parent::__construct(); } ``` ## model 通过加载器加载并返回一个model的实例。 函数原型 ```php /** * 获取一个model * @param $model string * @param $parent CoreBase */ function model($model, $parent) ``` 其中$model是Model的类名,根据SD的传统该类优先在app/Models中寻找,如果不存在则在Server/Models中寻找。 $parent是调用的容器,一般都是传入$this。 例子: ```php public function test_model() { $testModel = $this->loader->model('TestModel',$this); $testModel->timerTest(); } ``` Model是专门和数据打交道的模块。 ## task 通过加载器加载并返回一个task的代理。 函数原型 ```php /** * 获取一个task * @param $task * @return mixed|null|TaskProxy * @throws SwooleException */ public function task($task) ``` 其中$task是Task的类名,根据SD的传统该类优先在app/Tasks中寻找,如果不存在则在Server/Tasks中寻找。 例子: ```php public function test_task() { $testTask = $this->loader->task('TestTask'); $result = $testTask->test(); } ``` TestTask有个test方法,虽然说$testTask是个TaskProxy,但你可以把他当做是TestTask调用方法。 ## view 通过加载器加载并返回一个模板 函数原型 ```php /** * view 返回一个模板 * @param $template * @param array $data * @param array $mergeData * @return string */ public function view($template, $data = [], $mergeData = []) ``` 例子: ```php /** * html测试 */ public function http_html_test() { $template = $this->loader->view('server::404'); $this->http_output->end(template); } ```