我將向您展示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的導航視圖助手的isAllowed方法(最後一個事件附加到了Zend導航視圖助手的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(); ?>
我使用此代碼,它工作得很好。它是基於: