CI框架Hook实现简单权限控制
依据实际需求,需准备两个关键文件:一个是用于处理权限逻辑的Acl类,另一个是存放于config目录下的权限配置文件acl.php。
Acl类文件应放置于application/hook/acl.php路径中。同时,需在application/config/config.php中启用hook功能,并在同目录下的hook.php中进行具体配置。
第一步是开启hook功能,涉及修改config.php文件。
复制代码 代码如下: /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = TRUE;
第二步是配置hook.php文件,定义具体的钩子行为。
复制代码 代码如下: /* | ------------------------------------------------------------------------- | Hooks | ------------------------------------------------------------------------- | This file lets you define "hooks" to extend CI without hacking the core | files. Please see the user guide for info: | | http://codeigniter.com/user_guide/general/hooks.html | */ $hook['post_controller_constructor'] = array( 'class' => 'Acl', 'function' => 'auth', 'filename' => 'acl.php', 'filepath' => 'hooks' );
关于参数的详细说明可参考官方文档链接。此处特别需要注意的是post_controller_constructor这一触发点,可根据实际业务需求选择其他合适的钩子位置。
第三步是编写权限配置文件acl.php,并将其放置在config目录下。
复制代码 代码如下: $config['AUTH'] = array( SUPER_ADMIN => array( 'admin' => array('index', 'logout'), ), ADMIN => array( 'admin' => array('index', 'logout'), ), GUEST => array( 'admin' => array('index', 'logout'), ), );
上述配置仅为示例,非真实数据,请根据实际项目情况调整。主要变量名必须为$config,以便后续加载使用。
第四步是编写具体的权限控制Acl类。
复制代码 代码如下: class Acl { private $url_model; private $url_method; private $CI; function Acl() { $this->CI =& get_instance(); $this->CI->load->library('session'); $this->url_model = $this->CI->uri->segment(1); $this->url_method = $this->CI->uri->segment(2); } function auth() { $user = $this->CI->session->userdata('USER'); if(empty($user)) $user->status = 0; $this->CI->load->config('acl'); $AUTH = $this->CI->config->item('AUTH'); if(in_array($user->status, array_keys($AUTH))){ $controllers = $AUTH[$user->status]; if(in_array($this->url_model, array_keys($controllers))){ if(!in_array($this->url_method, $controllers[$this->url_model])){ show_error('您无权访问该功能,该错误已经被记录!点击返回'); } }else{ show_error('您无权访问该模块,该错误已经被记录!点击返回'); } } else show_error('错误的用户类型,该错误已经被记录!点击返回'); } }
整体结构大致如此,最终实现仍需结合具体应用场景进行调整。
开发过程中需注意以下关键点:
复制代码 代码如下: $this->CI =& get_instance();
以上仅实现了基础的权限控制逻辑,开发者可根据自身需求进行自由扩展和优化。