CodeIgniter在每个控制器中验证用户 [英] CodeIgniter authenticate the user in every Controller
问题描述
我在Codeigniter建立第一个专案,使用 Tank_auth 来处理我的CMS验证。
关于最佳实践的问题。目前,每个控制器中的每个函数具有以下结构:
public function add()
{
if($ this-> tank_auth-> is_logged_in())
{
$ data ['stuff'] ='stuff'
$ this-> load-> view('admin / cms_add',$ data);
} else
{
redirect('/ admin / login /');
}
}
有很多控制器,每个,它开始重复,我想知道这是否是正确的方法去,或者如果有一个更清洁的方法,确保非登录用户不能访问这些功能。
如果每个控制器中的每个方法
__ construct()
方法如下: public function __construct()
{
parent :: __ construct();
if(!$ this-> tank_auth-> is_logged_in()){
redirect('/ admin / login /');
}
}
您还可以扩展CI控制器并创建自定义 MY_Controller
并检查其中的if语句。那么控制器只接受已登录的用户,应该继承 My_Controller
:
应用程序/core/MY_Controller.php
:
class MY_Controller extends CI_Controller {
public function __construct()
{
//执行CI_Controller构造函数
parent :: __ construct();
if(!$ this-> tank_auth-> is_logged_in()){
redirect('/ admin / login /');
}
}
}
application / controllers / welcome.php
:
class Welcome extends MY_Controller {
function __construct()
{
parent :: __ construct();
}
function index()
{
$ this-> load-> view('welcome_message');
}
}
查看 CI用户指南了解详情。
I'm building my first project in Codeigniter, using Tank_auth to handle my CMS authentication.
It's working ok but I have a question about best practices. Currently, every function in every controller has the following structure:
public function add()
{
if ($this->tank_auth->is_logged_in())
{
$data['stuff'] = 'stuff';
$this->load->view('admin/cms_add',$data);
} else
{
redirect('/admin/login/');
}
}
With quite a few controllers, and a few functions in each, it's starting to get repetitive, and I wonder if this is the correct way to go about it, or if there's a cleaner method of ensuring non-logged in users can't access these functions.
Thanks in advance.
If every method in every controller
should check whether user is logged-in, you can use __construct()
method in each controllers as the following:
public function __construct()
{
parent::__construct();
if (! $this->tank_auth->is_logged_in()) {
redirect('/admin/login/');
}
}
You can also extend the CI Controller and create a custom MY_Controller
and check the if statement inside. then the Controllers only accept logged-in users, should inherit the My_Controller
:
application/core/MY_Controller.php
:
class MY_Controller extends CI_Controller {
public function __construct()
{
// Execute CI_Controller Constructor
parent::__construct();
if (! $this->tank_auth->is_logged_in()) {
redirect('/admin/login/');
}
}
}
application/controllers/welcome.php
:
class Welcome extends MY_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->view('welcome_message');
}
}
Take a look at CI user guide for more info.
这篇关于CodeIgniter在每个控制器中验证用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!