多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
#### 架构函数注入 我们在上一章了解了如何调用当前请求对象实例,现在通过依赖注入把当前的请求对象直接注入到控制器类中,然后使用`$this->request`代替`Request::instance()`来获取请求对象实例。 下面先看一段代码示例: ~~~ <?php namespace app\index\controller; use think\Request; class Index { protected $request; public function __construct(Request $request) { $this->request = $request; } public function hello() { return 'Hello,' . $this->request->param('name') . '!'; } } ~~~ 当我们访问 ~~~ http://tp5.com/index/index/hello/name/thinkphp ~~~ 页面输出结果显示: ~~~ Hello,thinkphp! ~~~ > 事实上,如果继承内置的系统控制器基类的话已经可以直接调用request属性了,在think\Controller类的架构方法里面已经使用了依赖注入,实现的原理是一样的。 当然,依赖注入不仅仅只是注入Request对象这么简单,任何一个对象都可以实现注入,而且可以同时注入多个对象示例。 如果当前的控制器类需进行邮件处理(假设我们有一个 `think\Email`类),那么可以在架构函数中进行注入: ~~~ <?php namespace app\index\controller; use think\Email; use think\Request; class Index { protected $request; protected $email; public function __construct(Request $request, Email $email) { $this->request = $request; $this->email = $email; } public function hello() { // 发送Hello邮件 // $this->email->sendMail($this->request->param('address'),'Hello'); return 'Hello,' . $this->request->param('name') . '!'; } } ~~~ `hello方法`中调用`Email类`的`sendMail方法`因为调试问题注释掉了,仅供参考。 架构函数的参数顺序并会不影响依赖注入。