codeigniter 检查每个控制器中的用户会话 [英] codeigniter check for user session in every controller
问题描述
我在我的一个控制器中有这个私人会话,用于检查用户是否登录:
I have this private session in one of my controllers that checks if a user is logged in:
function _is_logged_in() {
$user = $this->session->userdata('user_data');
if (!isset($user)) {
return false;
}
else {
return true;
}
}
问题是我有不止一个控制器.如何在其他控制器中使用此功能?在每个控制器中重新定义函数并不是很枯燥".
Problem is that I have more than one Controller. How can I use this function in those other controllers? Redefining the function in every Controller isn't very 'DRY'.
有什么想法吗?
推荐答案
另一种选择是创建一个基本控制器.将函数放在基本控制器中,然后从这里继承.
Another option is to create a base controller. Place the function in the base controller and then inherit from this.
要在 CodeIgniter 中实现此目的,请在应用程序的库文件夹中创建一个名为 MY_Controller.php 的文件.
To achieve this in CodeIgniter, create a file called MY_Controller.php in the libraries folder of your application.
class MY_Controller extends Controller
{
public function __construct()
{
parent::__construct();
}
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
}
然后让你的控制器从这个基本控制器继承.
Then make your controller inherit from this base controller.
class X extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function do_something()
{
if ($this->is_logged_in())
{
// User is logged in. Do something.
}
}
}
这篇关于codeigniter 检查每个控制器中的用户会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!