根據自己的實際情況,需要兩個文件,一個是權限控制類,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('您無權訪問該功能,該錯誤已經被記錄!點擊<a href="'. site_url('admin/logout') .'">返回</a>'); } }else{ show_error('您無權訪問該模塊,該錯誤已經被記錄!點擊<a href="'. site_url('admin/logout') .'">返回</a>'); } } else show_error('錯誤的用戶類型,該錯誤已經被記錄!點擊<a href="'. site_url('admin/logout') .'">返回</a>'); } }
整體上大體是這樣的形式,最后還是要根據自己的實際情況來確定。
需要注意的是:
$this->CI =& get_instance();