Thinkphp許可權控制類中_initialize()的調用原理

來源:互聯網
上載者:User

標籤:php thinkphp

在使用許可權認證的時候,我們會這樣編寫入權限類:


namespace Common\Common\Controller;
use Think\Controller;
use Think\Auth;

class AuthController extends Controller{
                protected function _initialize(){
                        //擷取登陸資訊
                        $uid = session(‘uid‘);
                        
                        if(empty($uid)){
                                $this->error(‘請先登陸!‘,U(‘Login/index‘),1);
                        }
                        
                        //如果是管理員,則不用驗證許可權了
                         if(session(‘gids‘) == ‘1‘){
                                return true;
                        } 
                        
                        //驗證許可權
                         $auth = new Auth();
                        if(!$auth->check(MODULE_NAME.‘/‘.CONTROLLER_NAME.‘/‘.ACTION_NAME,$uid)){
                                $this->error(‘沒有許可權‘,‘‘,1);
                        } 
                }
}


當我們初始化權限類別的時候,就會自動調用_initialize()函數。。。

但是,_initialize()並不是php原生的初始化自動調用的函數名,而__construct()才是。

我們再開啟權限類別繼承的Controller類,就有如下代碼:
public function __construct() {
        Hook::listen(‘action_begin‘,$this->config);
        //執行個體化視圖類
        $this->view     = Think::instance(‘Think\View‘);
        //控制器初始化
        if(method_exists($this,‘_initialize‘))
            $this->_initialize();
    }

仔細理解:Controller類中也沒有_initialize函數,而是在權限類別中自訂的這樣一個函數。

當我們初始化權限類別的時候,同時也就初始化了Controller類,於是觸發了__construct,在__construct中就判斷是否存在_initialize函數,如果存在,則調用,不存在,則忽略。。。
所以才會有初始化權限類別的時候,自動調用_initialize函數!


原創文章:http://bbs.51cto.com/thread-1501917-1.html 歡迎前來討論!

Thinkphp許可權控制類中_initialize()的調用原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.