This method is said in the official manual:
If your controller class inherits the \think\Controller class, you can define the controller initialization method _initialize, in the controller is executed first before the method is called. In fact, there are more than 5, it has also appeared in previous versions. Let’s talk to you about its implementation process.
Example
The following is an example given in the official manual:
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'; } }
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
\think\Controllerclass, plus this is initialization, so we first I thought of
__construct() in the \think\Controller
class. Let’s take a look at the code: <pre class="brush:php;toolbar:false">/**
* 架构函数
* @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);
}
}
}</pre>
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: <pre class="brush:php;toolbar:false">// 控制器初始化
if (method_exists($this, '_initialize')) {
$this->_initialize();
}</pre>
Has the truth emerged? !
In fact, when a child class inherits the parent class, it will naturally inherit the parent class's constructor without overriding the constructor. Correspondingly, it will be judged whether there is
_initialize in the current class.Methods are executed if available. This is the so-called
controller initialization principle. Extension
If the subclass inherits the parent class and rewrites the constructor method, pay attention to calling the parent class's
, otherwise it will not be used. The code is as follows:
public function __construct() { parent::__construct(); ...其他代码... }
SummaryA simple little design, here is a brief analysis, I hope it will be helpful to everyone.
Link
Related manual page:
http://www.kancloud.cn/manual/thinkphp5/118049