您好,欢迎访问一九零五行业门户网

CI框架中通过hook的方式实现简单的权限控制,cihook_PHP教程

ci框架中通过hook的方式实现简单的权限控制,cihook根据自己的实际情况,需要两个文件,一个是权限控制类,acl,另外一个是权限配置的文件acl.php放在了config这个目录下。
acl这个类放在了application/hook/acl.php。通过application/config/config.php文件开启hook,并且配置config这个目录下的hook.php文件。
1、开启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;
2、配置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这个值,可以根据情况选择不同的。
3、编写权限配置文件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,这样便于加载使用。
4、编写具体的权限控制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();
以上只是实现了简单的权限控制,小伙伴们可以根据自己的需求,自由扩展下吧。
http://www.bkjia.com/phpjc/939406.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/939406.htmltecharticleci框架中通过hook的方式实现简单的权限控制,cihook 根据自己的实际情况,需要两个文件,一个是权限控制类,acl,另外一个是权限配置的文...
其它类似信息

推荐信息