在 ZF2 路由配置中传递自定义变量


Pass custom variables in ZF2 routing config?

我正在考虑实现ACL的最佳方法。所以 - 我需要保护某些路线。有些路由仅供用户访问,有些路由可供来宾访问,有些路由可供管理员访问。

似乎最好的方法是在路由配置中添加一个$role变量。然后我会附加到路由后事件,获取 routeMatch,然后我会看看这个用户是否可以输入这个路由。

我该怎么做?我可以简单地像这样注入额外的变量吗:

'router' => array(
    'routes' => array(
        'route1' => array(
            'type' => 'Zend'Mvc'Router'Http'Regex',
            'options' => array(
                'regex' => '/some/route/1',
                'defaults' => array(
                    'controller' => 'Subscriber'Controller'View',
                    'action'     => 'route1',
                    'role'       => 'user', //extra
                ),
                'spec' => '/some/route/1',
            ),
        ),
        'route2' => array(
            'type' => 'Zend'Mvc'Router'Http'Regex',
            'options' => array(
                'regex' => '/some/route/2',
                'defaults' => array(
                    'controller' => 'Subscriber'Controller'View',
                    'action'     => 'route2',
                    'role'       => 'guest', //extra
                ),
                'spec' => '/some/route/2',
            ),
        ),
        //other routes....
    ),
),

是的,您可以像添加路由器密钥一样添加路由器密钥

'defaults' => array(
    'controller' => 'Subscriber'Controller'View',
    'action'     => 'route1',
    'role'       => 'user', //extra
),

然后你可以像这样检查它

public function onBootstrap(MvcEvent $e) {
    $application            = $e->getApplication();
    $eventManager = $application->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_ROUTE, function(MvcEvent $e) {
        $e->getRouteMatch()->getParam('role');
    });
}

但是,有为此制作的模块例如bjyoungblood/bjyAuthored,它与ZfcUser一起工作

你应该看看:ZfcRbac。这是有据可查的。