学习笔记一 简单的Zend_acl

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
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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值