前言
_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
會輸出
initdata
分析
因為使用必須要繼承\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(); ...其他代碼...}
總結
一個簡單的小設計,這裡拋磚引玉的分析下,希望對大家有協助。