If your Controller class inherits the \ think \ Controller class, you can define the Controller initialization method _ initialize and execute it before calling the Controller method. Preface
_ Initialize:
If your Controller class inherits the \ think \ Controller class, you can define the Controller initialization method _ initialize and execute it before calling the Controller method.
In fact, more than 5 has also appeared in earlier versions. let's talk about its implementation process.
Example
The following is an example 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
Output
init hello
If you access
Http: // localhost/index. php/index/Index/data
Output
initdata
Analysis
Because the use must inherit the \ think \ Controller class, and this is initialization, we first think of _ construct () in the \ think \ Controller class. let's look at the code together:
/*** Architecture function * @ param Request $ request Request object * @ 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; // The controller initializes if (method_exists ($ this, '_ initialize') {$ this-> _ initialize ();} // pre-operation method if ($ this-> beforeA CtionList) {foreach ($ this-> beforeActionList as $ method => $ options) {is_numeric ($ method )? $ This-> beforeAction ($ options): $ this-> beforeAction ($ method, $ options );}}}
Note that there is a controller initialization comment in the entire constructor, and the following code is the key to implementing this initialization:
// The controller initializes if (method_exists ($ this, '_ initialize') {$ this-> _ initialize ();}
What's the truth ?!
In fact, when the subclass inherits the parent class and does not overwrite the constructor, it naturally inherits the constructor of the parent class, to determine whether the _ initialize method exists in the current class. If yes, it will be executed. this is the so-called controller initialization principle.
Extension
If the child class inherits the parent class and the constructor is overwritten, you must call the _ construct () of the parent class. Otherwise, the code is as follows:
Public function _ construct () {parent ::__ construct ();... other code ...}
Summary
A simple and small design. I hope to help you with the analysis here.