0
我想要創建一個全局對象來代表Code Igniter中的當前用戶。該對象的構造函數採用用戶標識,該標識存儲在$_SESSION['user_id']
中。應該在Code Igniter中實例化一個全局對象嗎?
每次用戶訪問一個頁面時,我都想創建這個用戶對象。我應該在哪裏實例化它?我認爲在config/constants.php中實例化它,但有沒有更實用的標準/可靠的地方?
我想要創建一個全局對象來代表Code Igniter中的當前用戶。該對象的構造函數採用用戶標識,該標識存儲在$_SESSION['user_id']
中。應該在Code Igniter中實例化一個全局對象嗎?
每次用戶訪問一個頁面時,我都想創建這個用戶對象。我應該在哪裏實例化它?我認爲在config/constants.php中實例化它,但有沒有更實用的標準/可靠的地方?
一種選擇是創建一個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
}
}
謝謝你,這是一個好主意。 – 2012-03-28 18:53:23