前言
_initialize() 这个方法在官方手册里是这样说的:
如果你的控制器类继承了\think\controller类的话,可以定义控制器初始化方法_initialize,在该控制器的方法调用之前首先执行。
其实不止5,在之前的版本中也出现过,这里和大家聊一聊它的实现过程吧。
示例
下面是官方手册上给的示例:
namespace app\index\controller;
use think\controller;
class index extends controller
{
public function _initialize()
{
echo 'init<br/>';
}
public function hello()
{
return 'hello';
}
public function data()
{
return 'data';
}
}
如果访问
http://localhost/index.php/index/index/hello
会输出
init
hello
如果访问
http://localhost/index.php/index/index/data
会输出
init
data
分析
因为使用必须要继承\think\controller类,加上这个又是初始化,所以我们首先就想到了\think\controller类中的 __construct(),一起来看代码:
/**
* 架构函数
* @param request $request request对象
* @access public
*/
public function __construct(request $request = null)
{
if (is_null($request)) {
$request = request::instance();
}
$this->view = view::instance(config::get('template'), config::get('view_replace_str'));
$this->request = $request;
// 控制器初始化
if (method_exists($this, '_initialize')) {
$this->_initialize();
}
// 前置操作方法
if ($this->beforeactionlist) {
foreach ($this->beforeactionlist as $method => $options) {
is_numeric($method) ?
$this->beforeaction($options) :
$this->beforeaction($method, $options);
}
}
}
细心的你一定注意到了,在整个构造函数中,有一个控制器初始化的注释,而下面代码就是实现这个初始化的关键:
// 控制器初始化
if (method_exists($this, '_initialize')) {
$this->_initialize();
}
真相出现了有木有?!
其实就是当子类继承父类后,在没有重写构造函数的情况下,也自然继承了父类的构造函数,相应的,进行判断当前类中是否存在 _initialize 方法,有的话就执行,这就是所谓的控制器初始化的原理。
延伸
如果子类继承了父类后,重写了构造方法,注意调用父类的__construct()哦,否则是使用不了的,代码如下:
public function __construct()
{
parent::__construct();
...其他代码...
}
总结
一个简单的小设计,这里抛砖引玉的分析下,希望对大家有帮助。