use*_*224 7 session codeigniter
让我说在我的控制器名为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
}
Run Code Online (Sandbox Code Playgroud)
这不是漫长而乏味吗?有没有最终的方法来实现这一目标?
我看了链接
但似乎我仍然需要is_logged_in
在每种方法中应用检查.
感谢你们对我的帮助!
Esa*_*ija 11
在以下位置创建一个名为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
}
}
Run Code Online (Sandbox Code Playgroud)
然后,只要您创建新控制器,就可以决定它需要什么访问权限
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();
}
Run Code Online (Sandbox Code Playgroud)
这会大大减少代码重复,因为如果你需要另一个成员控制器,Book
你可以只扩展Member_Controller
.而不是必须在所有这些中进行检查.
你不一定需要这样做.只需将登录检查代码放在构造函数中,就可以了!
class Book extends CI_Controller
{
public function __construct()
{
if ($this->is_logged_in())
{
// redirect to home
}
}
public function get_book()
{
...
}
// The rest of the code...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5984 次 |
最近记录: |