CodeIgniter - 如何检查会话在每个方法使用 [英] CodeIgniter - How to check session to be used at every methods
问题描述
让我在控制器上命名为 Book ,我有很多方法,例如
get_book();
read_book();
remove_book();
Let say at my controller named Book, I have many methods, such as
get_book();
read_book();
remove_book();
可以在没有用户登录的情况下使用,我可以从会话中获取 user_id
。
No methods in the class can be used without user logged in, and I can get the user_id
from session.
strong>什么是/是否是检查 user_id
会话是否已设置,以便我可以使用方法的最佳方法?
My question is, what is/are the best ways to check the if the user_id
session is set so that I can use the methods?
现在我想创建一个 is_logged_in()
方法, if-else语句,如
As for now I am thinking of creating a is_logged_in()
method, and apply it to every methods with an if-else statement, like
if($this->is_logged_in()
{
//do something
}
else
{
//redirect to home
}
这是不是很长而乏味?有没有一个最终的方式来实现这个?
Isn’t it long and tedious? Is there an ultimate way to achieve this?
我读取链接
但似乎我仍然必须应用 is_logged_in
But it seems that I still have to apply the is_logged_in
check at every methods.
感谢您帮助我!
推荐答案
在 / application / core
中调用 MY_controller.php
(前缀可以在配置文件中编辑)的文件:
Create a file called MY_controller.php
(the prefix can be edited in config file) in /application/core
:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
//Initialization code that affects all controllers
}
}
class Public_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
//Initialization code that affects Public controllers. Probably not much needed because everyone can access public.
}
}
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
//Initialization code that affects Admin controllers I.E. redirect and die if not logged in or not an admin
}
}
class Member_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
//Initialization code that affects Member controllers. I.E. redirect and die if not logged in
}
}
class Book extends Member_Controller {
//Code that will be executed, no need to check anywhere if the user is logged in.
//The user is guaranteed to be logged in if we are executing code here.
//If you define a __construct() here, remember to call parent::__construct();
}
这样可以减少代码重复,因为如果你需要另一个成员控制器 Book
你可以扩展 Member_Controller
。而不是必须在所有的检查。
This cuts code duplication a lot, since if you need another member controller other than Book
you can just extend the Member_Controller
. Instead of having to do the checks in all of them.
这篇关于CodeIgniter - 如何检查会话在每个方法使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!