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.’有权下载电影.合法访问’);
}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值