如果有人用過laravel起便,那么一定知道中間件念脯,我們用他做授權管理特別爽狞洋。我在使用CI時,也在想CI中是否也有類似laravel中間件的方法绿店。
我一開始用使用繼承控制器吉懊,在父類的__construct方法里面做授權判斷。
后來隨著我對CI的了解假勿,發(fā)現(xiàn)有個叫鉤子的東西惕它。我目前的理解是這個鉤子是在運行我們創(chuàng)建的控制前執(zhí)行的方法。
使用的方法記錄下:
1废登、在config.php
中打開鉤子擴展
設置為TRUE
2绑蔫、在hooks.php
中添加鉤子配置
$hook['post_controller_constructor'][] = array(
'class' => 'ManageAuth', //類名
'function' => 'auth', //執(zhí)行的方法
'filename' => 'ManageAuth.php', //文件名
'filepath' => 'hooks' //文件路徑束析,默認是application/hooks
);
3浑玛、創(chuàng)建你的鉤子程序文件ManageAuth.php
class ManageAuth
{
private $CI;
public function __construct()
{
$this->CI = &get_instance(); //獲取CI對象
}
//權限認證
public function auth()
{
$this->CI->load->helper('url');
if(preg_match("/welcome.*/i",uri_string()))
{
//需要進行權限檢查的url
$this->CI->load->library('session');
if(!$this->CI->session->userdata('username'))
{
//用戶未登錄
redirect('login');
return;
}
}
}
最后再附上 鉤子的官方文檔,寫的很清楚兆蕉。
http://codeigniter.org.cn/user_guide/general/hooks.html
[獲取授權]