本文主要是介绍CI框架钩子功能——權限控制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.相關資料http://codeigniter.org.cn/user_guide/general/hooks.html
2.打开權限控制功能在 application/config/config.php 文件中设定:
$config['enable_hooks'] = TRUE;
3.在項目目錄下的application/config/hoos.php文件定義相關的鈎子,例:
$hook['post_controller_constructor'] = array('class' => 'Acl','function' => 'filter','filename' => 'acl.php','filepath' => 'hooks',
);
4.在項目目錄下的
application/hooks和application/config下添加acl.php文件
以下為application/hooks/acl.php的相關代碼
<?php
class Acl
{private $url_model;//所访问的模块,如:musicprivate $url_method;//所访问的方法,如:createprivate $url_param;//url所带参数 可能是 1 也可能是 id=1&name=testprivate $CI;function Acl(){$this->CI = & get_instance();$this->CI->load->library('session');$url = $_SERVER['PHP_SELF'];$arr = explode('/', $url);$arr = array_slice($arr, array_search('index.php', $arr) + 1, count($arr));$this->url_model = isset($arr[0]) ? $arr[0] : '';$this->url_method = isset($arr[1]) ? $arr[1] : 'index';$this->url_param = isset($arr[2]) ? $arr[2] : '';}/*** 權限過濾*/function filter(){$user = $this->CI->session->userdata('user');if (empty($user)){//游客guest$role_name = 'guest';} else {//admin teacher student$role_name = $user->role;}$this->CI->load->config('acl');$acl = $this->CI->config->item('acl');$role = $acl[$role_name];$acl_info = $this->CI->config->item('acl_info');if (array_key_exists($this->url_model, $role) && in_array($this->url_method, $role[$this->url_model])){;} else {//无权限,给出提示,跳转url$this->CI->session->set_flashdata('info', $acl_info[$role_name]['info']);redirect($acl_info[$role_name]['return_url']);}}}?>
以下為application/config/acl.php的相關代碼
<?php
//權限映射 start
//遊客
$config['acl']['guest'] = array('' => array('index'),'users' => array('login')
);
//管理員
$config['acl']['admin'] = array();
//權限映射 end//配置權限不夠的提示信息以及跳轉url start
$config['acl_info']['guest'] = array('info' => '需要登錄以繼續','return_url' => 'users/login'
);$config['acl_info']['more_role'] = array('info' => '需要更高權限以繼續','return_url' => 'users/up'
);
// 配置權限不夠的提示信息以及跳轉url end?>
之後若需要給用戶添加頁眉權限時,在 application/config/acl.php修改即可
这篇关于CI框架钩子功能——權限控制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!