Model view controller 防止代码重复CodeIgniter验证
可能重复:Model view controller 防止代码重复CodeIgniter验证,model-view-controller,validation,codeigniter,Model View Controller,Validation,Codeigniter,可能重复: 框架:CI(CodeIgniter) 情况: 我有4页(控制器),即: home 登录 仪表板 editprofile 访问 主页可供所有类型的用户访问,无论是否登录 登录必须只有在未经身份验证的情况下才能访问 仪表板和editprofile只能由学生(经过身份验证的用户)访问 我对我的控制器进行了如下验证: if($this->session->userdata('isLoggedIn')){ // stay here do the function }
框架:CI(CodeIgniter) 情况: 我有4页(控制器),即:
home
登录
仪表板
editprofile
访问
- 主页可供所有类型的用户访问,无论是否登录
- 登录必须只有在未经身份验证的情况下才能访问
- 仪表板和editprofile只能由学生(经过身份验证的用户)访问
if($this->session->userdata('isLoggedIn')){
// stay here do the function
} else {
// leave this page
header('Location:'.base_url().'login');
}
<?PHP
class User_Controller extends MY_Controller
{
function __construct()
{
parent::__construct();
if (!$this->session->userdata('is_logged_in')) {
$this->session->set_flashdata('message', "I'm sorry, but you must be logged in to view that page.");
redirect("/");
}
}
}
我在我的函数索引(){}
中有它
但是随着我开发这个系统,随着我创建更多的方法,更多的控制器,它变得越来越混乱。。
因为你需要用这个
if($this->session->userdata('isLoggedIn')){
// stay here do the function
} else {
// leave this page
header('Location:'.base_url().'login');
}
每次你有了方法
我在stackoverflow中读了几个问题。。。唯一最好的答案是:链接这里
上面说我必须用装饰图案来装饰。。。但是我不清楚该怎么做。为每种类型的用户创建不同的基本控制器,然后只需设置一次该语句。我们的用户控制器如下所示:
if($this->session->userdata('isLoggedIn')){
// stay here do the function
} else {
// leave this page
header('Location:'.base_url().'login');
}
<?PHP
class User_Controller extends MY_Controller
{
function __construct()
{
parent::__construct();
if (!$this->session->userdata('is_logged_in')) {
$this->session->set_flashdata('message', "I'm sorry, but you must be logged in to view that page.");
redirect("/");
}
}
}
非常感谢,我想这就是答案。