我想在Code Igniter中创建一个表示当前用户的全局对象。对象的构造函数采用用户id,该id存储在$_SESSION['user_id']
中。
每次用户访问页面时,我都希望创建这个用户对象。我应该在哪里实例化它?我认为在config/contents.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
}
}