Zend Framework之Zend_Auth,Zend_Acl实现用户的授权和操作

Zend Framework之Zend_Auth,Zend_Acl实现用户的授权和操作

index.php:
<?php
error_reporting(E_ALL|E_STRICT);
date_default_timezone_set(‘Asia/Shanghai’);
set_include_path(‘.’ .PATH_SEPARATOR .’./library’.PATH_SEPARATOR .’./application/models/’.PATH_SEPARATOR . get_include_path());
require_once ‘Zend/Loader.php’;
Zend_Loader::registerAutoload();//设置Zend Framework 自动载入类文件
$registry = Zend_Registry::getInstance();
$view = new Zend_View();
$view->setScriptPath(‘./application/views/scripts/’);//设置模板显示路径
$registry[‘view’] = $view;//注册View

//初始化访问控制连
$acl = new Zend_Acl;
$acl->add(new Zend_Acl_Resource(‘video’));
$acl->add(new Zend_Acl_Resource(‘notices’));
//上面对应我的两个module,一个video,一个notices
$acl->addRole(new Zend_Acl_Role(‘guest’));
$acl->addRole(new Zend_Acl_Role(‘user’), ‘guest’);
$acl->addRole(new Zend_Acl_Role(‘staff’), ‘user’);//继承关系staff,user,guest
$acl->addRole(new Zend_Acl_Role(‘admin’));
$acl->allow(‘guest’, array(‘video’, ‘notices’), ‘view’);//guest只有view权利
$acl->allow(‘user’, array(‘video’), array(‘reply’, ‘download’));
$acl->allow(‘staff’, array(‘video’, ‘notices’), array(‘delete’, ‘update’));
$acl->allow(‘admin’);

//验证权限,如果没有登录则以游客身份登录
$auth = Zend_Auth::getInstance();
if(!$auth->hasIdentity())
{
$auth->getStorage()->write((object)array(‘username’ => ‘Guest’,
‘role’ => ‘guest’,
‘truename’ => ‘游客’
));
}
$router = new Zend_Controller_Router_Rewrite();
//$router->addRoute(‘root’,new Zend_Controller_Router_Route(‘/’,array(‘module’ =>’News’, ‘controller’ => ‘Index’, ‘Action’ => ‘index’))); //也是给出默认控制器的
//设置控制器
$frontController =Zend_Controller_Front::getInstance();
$frontController->setBaseUrl(‘/zendframework’)//设置基本路径
->setParam(‘noViewRenderer’, true)
->setRouter($router)//1
->setParam(‘Zend_Acl’, $acl)//2
->setParam(‘Zend_Auth’, $auth)//3
->returnResponse(false)//4
->setControllerDirectory(‘./application/controllers’)
->throwExceptions(true)
->dispatch();
IndexController.php:
<?php
header(‘Content-Type: text/html; charset=utf-8’);
class IndexController extends Zend_Controller_Action
{
function init()
{
$this->registry = Zend_Registry::getInstance();
$this->view = $this->registry[‘view’];
$this->view->baseUrl = $this->_request->getBaseUrl();
}

function indexAction()
{
$acl = $this->getInvokeArg(‘Zend_Acl’);
$role = $this->getInvokeArg(‘Zend_Auth’)->getStorage()->read()->role;//取得角色
if(!$acl->isAllowed($role, ‘video’, ‘download’))//判断用户有没有电影的下载权利
$this->getResponse()->appendBody($role.’没有video的下载权利,’.$role.’为游客登录!’);
else
$this->getResponse()->appendBody($role.’有权下载电影.合法访问’);
}

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注