我正在努力了解 ZF2 中的模块路由。
目前我只能为单个操作创建一个 Controller ,并且正在努力找出这个路由。我查看了其他模块和插件,我有点明白了,只需要轻轻一推就可以“明白”。
在这个例子中,我试图路由到两个 Action :indexAction 和 cmstoolsAction
本质上,用户导航到:
/affiliates/overview
/affiliates/cmstools
错误是:
The requested URL could not be matched by routing.
我认为我遇到困难的地方首先是理解 MVC 的工作原理并迷失在细节中。手册中的信息太多,有点让人不知所措。
无论如何 - 非常感谢任何输入!
模块结构图:
我的 Controller 看起来像这样:
<?php
namespace Affiliates\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class AffiliatesController extends AbstractActionController
{
//Overview page
public function IndexAction()
{
}
public function CmstoolsAction()
{
}
}
我的模块配置如下所示:
<?php
return array(
'view_manager' => array(
'template_path_stack' => array(
'affiliates' => __DIR__ . '/../view',
),
),
'controllers' => array(
'invokables' => array(
'Affiliates\Controller\Affiliates' =>
'Affiliates\Controller\AffiliatesController'
),
),
'router' => array(
'routes' => array(
'affiliates' => array(
'type' => 'Literal',
'options' => array(
'route' => '/overview',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'cmstools' => array(
'type' => 'Literal',
'options' => array(
'route' => '/cmstools',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'cmstools',
),
),
),
),
),
),
),
);
最佳答案
路由配置是这里唯一重要的部分。目前,您有一个用于 /overview
的路由,它有一个用于 /cmstool
的子路由。这将匹配以下 URL:
/overview
/overview/cmstool
不完全是你想要的。
您可以通过几种不同的方式进行配置。最接近您当前拥有的是 /affiliates
的路线,有两条子路线,一条用于您的每个操作。为此的配置是:
'router' => array(
'routes' => array(
'affiliates' => array(
'type' => 'Literal',
'options' => array(
'route' => '/affiliates',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'index',
),
),
'child_routes' => array(
'overview' => array(
'type' => 'Literal',
'options' => array(
'route' => '/overview',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'index',
),
),
),
'cmstools' => array(
'type' => 'Literal',
'options' => array(
'route' => '/cmstools',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'cmstools',
),
),
),
),
),
),
),
此配置包含三个路由:affiliates
、overview
和cmstools
。后两者都是affiliates的子路由。请注意,我从 affiliates 路由中删除了 'may_terminate' => true,
行。这决定了 affiliates 路由是否会自行匹配(即 URL /affiliates
是否有效)。既然你没有列出这个,我假设你不希望它列出。
您可以配置它的另一种方法是简单地创建两个文字路由,每个 URL 一次(根本不使用子路由):
'router' => array(
'routes' => array(
'overview' => array(
'type' => 'Literal',
'options' => array(
'route' => '/affiliates/overview',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'index',
),
),
),
'cmstools' => array(
'type' => 'Literal',
'options' => array(
'route' => '/affiliates/cmstools',
'defaults' => array(
'controller' => 'Affiliates',
'action' => 'cmstools',
),
),
),
),
),
关于zend-framework2 - ZF2 - Zend Framework 2,了解路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23280087/