假设我的控制器名为Book,我有很多方法,比如get_book();
read_book();
remove_book();
如果没有用户登录,则无法使用类中的任何方法,我可以获得user_id
来自会话。
我的问题是,检查是否存在的最佳方法是什么user_id
设置会话以便我可以使用这些方法?
至于现在我正在考虑创建一个is_logged_in()
方法,并使用 if-else 语句将其应用于每个方法,例如
if($this->is_logged_in()
{
//do something
}
else
{
//redirect to home
}
是不是又长又乏味?有没有最终的方法来实现这一目标?
我读了链接
codeigniter 检查每个控制器中的用户会话
但看来我还是要申请is_logged_in
检查每个方法。
感谢你们对我的帮助!
创建一个名为MY_controller.php
(前缀可以在配置文件中编辑)/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
。而不必对所有这些进行检查。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)