2012-03-28 5 views
0

コードイグナイターで現在のユーザーを表すグローバルオブジェクトを作成したいとします。オブジェクトのコンストラクタはユーザIDをとり、$_SESSION['user_id']に格納されます。コードイグナイターでグローバルオブジェクトをインスタンス化する場所はどこですか?

ユーザーがページにアクセスするたびに、このユーザーオブジェクトを作成します。どこでインスタンス化する必要がありますか? config/constants.phpでインスタンス化すると思いますが、インスタンス化するための標準/信頼性の高い場所がありますか?

答えて

3

1つのオプションは、他のすべてのコントローラが継承するMY_Controllerを作成することです。ユーザオブジェクトはMY_Controllerの中でインスタンス化することができ、したがって、それを継承するすべてのコントローラで使用可能になります。例簡体

class MY_Controller extends CI_Controller { 

    public $user; 

    function __construct(){ 
     parent::__construct(); 

     // Get the current user (pseudo code, obviously) 
     $this->user = $this->user_model->get_user($id); 
    } 

} 

class Some_other_controller extends My_Controller { 

    function __construct(){ 
     parent::__construct(); 
     // $user is available throughout this controller 
    } 

} 

class Another_controller extends My_Controller { 

    function __construct(){ 
     parent::__construct(); 
     // $user is available throughout this controller 
    } 

} 
+0

はそれは良いアイデアです、ありがとうございます。 –

関連する問題