[英]Zend2 Routing __NAMESPACE__ doesn't work or be ignored
我在Zend2中使用此配置作为我的应用程序模块配置,这是非常正常的,并且每个人都建议作为标准路由规则:
'controllers' => array(
'invokables' => array(
'Application\Controller\Index' => 'Application\Controller\IndexController',
),
),
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'application' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
home
路由工作正常。 但对于http://localhost/application
我得到:
索引(解析为无效的控制器类或别名:索引)
对于http://localhost/application/index/index
我得到:
index(解析为无效的控制器类或别名:index)
如果我改变这个:
'application' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
对此:
'application' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
正如您对http://localhost/application
所知,它可以像home
网址一样正常工作
如果我用这个:
'controllers' => array(
'invokables' => array(
'index' => 'Application\Controller\IndexController',
),
),
如你所知,配置将合并,我应该在项目中只有一个索引控制器。
为什么行'__NAMESPACE__' => 'Application\\Controller',
被忽略,它只在控制器数组中查找哪个不存在的索引或索引?
编辑:
与其他项目相比,我将其添加到Application/Module.php
:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
它现在有效,但我需要和解释。 是解决方案吗? 我的意思是我应该将它添加到项目中的Module.php
文件之一,以使路由规则正常工作吗? 为什么没有它, __NAMESPACE__
将在路由规则中被忽略?
您已经找到了解决方案,添加ModuleRouteListener
是正确的做法。 可以在此侦听器中的onRoute
方法的说明中找到解释:
侦听“route”事件并确定模块名称空间是否应该添加到控制器名称之前。
如果路由匹配包含与
MODULE_NAMESPACE
常量匹配的参数键,则该值将通过命名空间分隔符添加到匹配的控制器参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.