我複製/粘貼KohanaPHP的主應用程序控制器的代碼,假設我們已經包含了Zend_ACL。
請注意我擁有基於用戶的權限,而不是基於組的權限......雖然這可以很容易地編輯。
<?php
defined('SYSPATH') OR exit('No direct script access.');
class Controller_Application extends Controller_Template
{
protected static $acl;
public $template = 'default';
public function before()
{
parent::before();
session_start();
self::$acl = new Zend_Acl();
$this->set_permissions($_SESSION['userid']);
}
protected function check_access($resource, $privilege, $redirect = TRUE)
{
$permission = (self::$acl->has($resource) AND self::$acl->isAllowed($_SESSION['userid'], $resource, $privilege));
if (!$permission AND $redirect)
$this->request->redirect('user/denied');
elseif (!$permission AND !$redirect)
return FALSE;
elseif ($permission AND !$redirect)
return TRUE;
}
protected function set_permissions($user_id)
{
$result = DB::select()
->from('permissions')
->where('user_id', '=', $user_id)
->execute()
->as_array();
self::$acl->addRole(new Zend_Acl_Role($user_id));
foreach ($result AS $permission)
{
if (!self::$acl->has($permission['resource']))
self::$acl->add(new Zend_Acl_Resource($permission['resource']));
self::$acl->allow($user_id, $permission['resource'], $permission['privilege']);
}
}
}
?>
然後我檢查這樣的控制器訪問:$this->check_access('events', 'add');
。