我将向您展示 ZfcRbac 如何与 (ZF2) Zend/Navigation 一起工作。您在数据库中定义了权限,这就是我将省略此部分的原因。
定义您的导航添加页面和权限:
配置/global.phpPHP:
return array(
'navigation' => array(
'default' => array(
array(
'label' => 'Contracts',
'route' => 'contract',
'action' => 'list',
'permission' => 'contract.list',
'pages' => array(
array(
'label' => 'New contract',
'route' => 'contract',
'action' => 'add',
'permission' => 'contract.add',
)
)
)
)
),
'service_manager' => array(
'factories' => array(
'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
)
)
);
创建一个监听器(/module/Application/src/Application/Authorization/RbacListener.php):
<?php
namespace Application\Authorization;
use Zend\EventManager\EventInterface;
use Zend\Navigation\Page\AbstractPage;
use ZfcRbac\Service\AuthorizationServiceInterface;
class RbacListener
{
/**
* @var AuthorizationServiceInterface
*/
protected $authorizationService;
/**
* @param AuthorizationServiceInterface $authorizationService
*/
public function __construct(AuthorizationServiceInterface $authorizationService)
{
$this->authorizationService = $authorizationService;
}
/**
* @param EventInterface $event
* @return bool|void
*/
public function accept(EventInterface $event)
{
$page = $event->getParam('page');
if (!$page instanceof AbstractPage) {
return;
}
$permission = $page->getPermission();
if (is_null($permission)) {
$event->stopPropagation();
return false;
}
$event->stopPropagation();
return $this->authorizationService->isGranted($permission);
}
}
为 RbacListener 创建一个工厂 (/module/Application/src/Application/Factory/RbacListenerFactory.php):
<?php
namespace Application\Factory;
use Application\Authorization\RbacListener;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class RbacListenerFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$authorizationService = $serviceLocator->get('ZfcRbac\Service\AuthorizationService');
return new RbacListener($authorizationService);
}
}
将您的 RbacListenerFactory 添加到您的 ServiceManager (/module/Application/config/module.config.php):
<?php
return array(
'service_manager' => array(
'factories' => array(
'Application\Authorization\RbacListener' => 'Application\Factory\RbacListenerFactory',
),
),
);
将事件附加到 Zend Navigation View Helper 的 isAllowed 方法(最后将事件附加到 Zend Navigation View Helper 的 isAllowed 方法):
<?php
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$sharedEventManager = $eventManager->getSharedManager;
$serviceManager = $application->getServiceManager();
$rbacListener = $serviceManager->get('Application\Authorization\RbacListener');
$sharedEventManager->attach(
'Zend\View\Helper\Navigation\AbstractHelper',
'isAllowed',
array($rbacListener, 'accept')
);
}
在视图或布局中呈现菜单:
<?php echo $this->navigation('navigation')->menu(); ?>
我正在使用这段代码,它工作得很好。它基于: