Foreword
_initialize() This method is said in the official manual:
If your controller class inherits the thinkController class, you can define the controller initialization method _initialize, which is executed first before the method of the controller is called. .
In fact, there are more than 5, it has also appeared in previous versions. Let me talk to you about its implementation process.
Example
The following is the example given in the official manual:
namespace app\index\controller; use think\Controller; class Index extends Controller { public function _initialize() { echo 'init
'; } public function hello() { return 'hello'; } public function data() { return 'data'; } }
If you access
http://localhost/index.php/index/Index/hello
, it will output
init hello
If you access
http://localhost/index .php/index/Index/data
will output
init data
Analysis
Because the use must inherit the thinkController class, plus this is initialization, so we first thought of __construct() in the thinkController class, let’s take a look at the code :
/** * 架构函数 * @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 you are careful, you must have noticed that in the entire constructor, there is a comment for controller initialization, and the following code is the key to achieving this initialization:
// 控制器初始化 if (method_exists($this, '_initialize')) { $this->_initialize(); }
Has the truth emerged? !
In fact, when a child class inherits the parent class, it will naturally inherit the parent class's constructor without rewriting the constructor. Correspondingly, it will be judged whether there is an _initialize method in the current class. If so, Execution, this is the principle of so-called controller initialization.
Extension
If the subclass inherits the parent class and rewrites the constructor method, be careful to call the parent class's __construct(), otherwise it will not be used. The code is as follows:
public function __construct() { parent::__construct(); ...其他代码... }
Summary
A simple little design, Here is a brief analysis, I hope it will be helpful to everyone.