时间:2021-07-01 10:21:17 帮助过:2人阅读
- 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();
- ...其他代码...
- }
总结
一个简单的小设计,这里抛砖引玉的分析下,希望对大家有帮助。