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了。
3.使用简单的ACL
使用ACL非常简单,仅仅需要使用inAllowed方法加一个role和resource和一个权限。
唯一麻烦的是定义role,resource和privilege。
我们怎样定义role呢?其实非常简单:使用if-clause,如果是登陆的用户那么role就是用户,其余的是游客
那么resource呢?通过这个例子,我们定义了resource是文件,在这里我们可以建立一个page.php文件和一个news.php文件
page检查page resource,news 可以检查news resource。
权限,当load页面是你能够使用view权限,代码能够查看其他的privilege,比如是否有comment权限使用comment box。
$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
}
这个例子用于普通的php页面,下面部分是介绍在ZF中使用acl
4. 在ZF中使用
一般情况下我们需要建立一个小的插件用来检查acl
在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, 现在我们把它加入到bootstrap里
$acl = new My_Acl();
//assuming $fc is the front controller
$fc->registerPlugin(new My_Plugin_Acl($acl));
OK 现在每个request都要通过acl认证,如果过没有view权限将不能访问。
当我们想为某个特别的页面加入权限时,应当在action里加入
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');
}
想一下当你把这段代码加入到auth认证里会很方便。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8225983/viewspace-662739/ ,如需转载,请注明出处,否则将追究法律责任。