2014-01-29 51 views
0

所以我有一个模块,名为用户,并在这个模块内部我有一些控制器,现在我有一个注销控制器,我想创建网址(domain.tld /用户/注销)在我看来这个控制器。我想是这样的:ZF2网址视图帮手没有定义的路由

$this->url("user",array("controller" => "logout")); //This doesn't work 

我也试过这样:

$this->url("user/logout"); //This doesn't work since there isn't a child route defined for the user 

所以我的问题是,是否有使用url视图助手没有在module.config.php

定义的路由定义URL的选项

这里是我的module.config.php

return array(
    'router' => array(
     'routes' => array(
      'register' => array(
       'type' => 'Zend\Mvc\Router\Http\Literal', 
       'options' => array(
        'route' => '/user', 
        'defaults' => array(
         'controller' => 'User\Controller\Index', 
         'action' => 'index', 
        ), 
       ), 
      ), 
      'user' => array(
       'type' => 'Literal', 
       'options' => array(
        'route' => '/user', 
        'defaults' => array(
         '__NAMESPACE__' => 'User\Controller', 
         'controller' => 'Index', 
         'action' => 'index', 
        ), 
       ), 
       'may_terminate' => true, 
       'child_routes' => array(
        'default' => array(
         'type' => '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(
          ), 
         ), 
        ), 

回答

3

尝试取消片段了解路由的功能。您要访问的child_route称为default。由于这个原因,基本路线必须是

$this->url('user/default'); 

然而,因为没有defaults分配,你还需要声明所需的参数controlleraction。这意味着你的路由有看起来类似的东西:

$this->url('user/default', array('controller' => 'Foo', 'action' => 'Bar')); 

您定义的user/default路线的方式是不是真的那么好了。 $this->url('user/default')的第一个例子实际上会创建url domain.com/user/,这对于路由器来说是一个有效的URL,但是由于缺少参数,您的controller很可能会失败。基本上我建议你不要让控制器部分可选,但只有动作和定义默认动作。

'route' => '/:controller[/:action]' 
'defaults' => array(
    'action' => 'index' 
) 

这样,未来在所有的请求将保证始终匹配特定的控制器和它的indexAction()。当然你应该考虑只对这条路线下的所有控制器使用这个动作。

+0

Woaw,很棒的知识,真的很感激它,谢谢它的作品! – Uffo