ThinkPHP5之 _initialize() 初始化方法詳解

來源:互聯網
上載者:User
前言
_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();    ...其他代碼...}

總結
一個簡單的小設計,這裡拋磚引玉的分析下,希望對大家有協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.