ACL 学习笔记
2010_05_14,转载至codeutopia.
1. 误区
许多人认为ACL的“resource” ,“privilege” 和controller,action相似。这是不正确的。
在Zend中resource可以是任何事物:一个controller,一个file和一个mondel……
Privilige也一样,当resource是一个controller时privilege就是一个action,当resource是个model或file时privilige就是“write和read”。
在今后的学习中会接触到这些用法。
2. 创建一个简单的ACL
刚刚我们提到Zend_acl由resource,privilige和新加的role构成。
resource可以被我们认为是controller,files或其他。privilige定义了访问这些resource的等级。role决定了谁可以用privilige去访问resource,role可以是一个用户或者一个组或者是任何你想定义的东西。
这里介绍最简单的使用方法。这种方法适用于一个simple cases
1. 误区
许多人认为ACL的“resource” ,“privilege” 和controller,action相似。这是不正确的。
在Zend中resource可以是任何事物:一个controller,一个file和一个mondel……
Privilige也一样,当resource是一个controller时privilege就是一个action,当resource是个model或file时privilige就是“write和read”。
在今后的学习中会接触到这些用法。
2. 创建一个简单的ACL
刚刚我们提到Zend_acl由resource,privilige和新加的role构成。
resource可以被我们认为是controller,files或其他。privilige定义了访问这些resource的等级。role决定了谁可以用privilige去访问resource,role可以是一个用户或者一个组或者是任何你想定义的东西。
这里介绍最简单的使用方法。这种方法适用于一个simple cases
class My_Acl extends Zend_Acl {
public function __construct() {
//Add a new role called "guest"
$this->addRole(new Zend_Acl_Role('guest'));
//Add a role called user, which inherits from guest
$this->addRole(new Zend_Acl_Role('user'), 'guest');
//Add a resource called page
$this->add(new Zend_Acl_Resource('page'));
//Add a resource called news, which inherits page
$this->add(new Zend_Acl_Resource('news'), 'page');
//Finally, we want to allow guests to view pages
$this->allow('guest', 'page', 'view');
//and users can comment news
$this->allow('user', 'news', 'comment');
}
}
现在我们就能通过实例化这个类使用acl了。
$role = 'guest';
if(isset($_SESSION['auth']))
$role = 'user';
$acl = new My_Acl();
if($acl->isAllowed($role, 'news', 'comment')) {
//Some code here to display a news box
}
在library/My/Controller/Plugin/文件夹下建立Acl.php
class My_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
private $_acl = null;
public function __construct(Zend_Acl $acl) {
$this->_acl = $acl;
}
public function preDispatch(Zend_Controller_Request_Abstract $request) {
//As in the earlier example, authed users will have the role user
$role = (Zend_Auth::getInstance()->hasIdentity())
? 'user'
: 'guest';
//For this example, we will use the controller as the resource:
$resource = $request->getControllerName();
if(!$this->_acl->isAllowed($role, $resource, 'view')) {
//If the user has no access we send him elsewhere by changing the request
$request->setModuleName('auth')
->setControllerName('auth')
->setActionName('login');
}
}
}
$acl = new My_Acl();
//assuming $fc is the front controller
$fc->registerPlugin(new My_Plugin_Acl($acl));
public function someAction() {
$role = (Zend_Auth::getInstance()->hasIdentity())
? 'user'
: 'guest';
//assuming $this->_acl contains the acl
$this->view->canComment = $this->_acl->isAllowed($role, 'news', 'comment');
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8225983/viewspace-662739/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/8225983/viewspace-662739/