我想以多个字符串路由到同一控制器的方式配置我的 Zf2 应用程序。例如,www.mysite.com/this 和 www.mysite.com/that 都路由到同一个控制器,并可以使用 $this->参数捕获这个和那个。我将如何完成这样的事情?我是否需要 2 个单独的路由声明?
'directory' => [
'type' => 'ZendMvcRouterHttpLiteral',
'options' => [
'route' => '/string1 || /string2 || /string3',
'defaults' => [
'controller' => 'ApplicationControllerMyController',
'action' => 'index'
],
],
]
最简单的解决方案IMO是:
'varcatcher' => [
'type' => 'Segment',
'options' => [
'route' => '[/[:tail]]',
'defaults' => [
'controller' => 'ApplicationControllerIndex',
'action' => 'catch',
'module' => 'Application',
],
'constraints' => [
'tail' => '[a-zA-z0-9_-]*'
],
],
'may_terminate' => true,
],
然后在你的行动中处理它:
public function catchAction(){
die( $this->params()->fromRoute('tail') );
}
因为ZF2航线是后进先出。 最好先插入它,然后处理您需要"捕获"的任何情况。
提到LIFO,是因为如果您在路由器阵列中定义"之后"的路由,这些路由将位于捕获全部之前,如果我没看错您的问题,这似乎是有益的。
干杯!亚历克斯
您可以使用 Zend\Mvc\Router\Http\Regex 路由类型,而不是 Literal 路由类型,并执行以下操作
'directory' => [
'type' => 'ZendMvcRouterHttpRegex',
'options' => [
'route' => '/string(?<id>[0-9]+)',
'defaults' => [
'controller' => 'ApplicationControllerMyController',
'action' => 'index'
],
],
]
根据文字路由的定义,创建 3 条路由:
'directory1' => [
'type' => 'ZendMvcRouterHttpLiteral',
'options' => [
'route' => '/string1',
'defaults' => [
'controller' => 'ApplicationControllerMyController',
'action' => 'index',
],
],
],
'directory2' => [
'type' => 'ZendMvcRouterHttpLiteral',
'options' => [
'route' => '/string2',
'defaults' => [
'controller' => 'ApplicationControllerMyController',
'action' => 'index',
],
],
],
'directory3' => [
'type' => 'ZendMvcRouterHttpLiteral',
'options' => [
'route' => '/string3',
'defaults' => [
'controller' => 'ApplicationControllerMyController',
'action' => 'index',
],
],
],