Zend 框架如何使 url 正确路由到我定义的操作?

Zend framework how can i make the url to get correctly routed to my defined action?

我正在尝试路由,但无法正确路由。

当我要去 www.example.com/nl/over-ons 时它无法去 class AboutController extends AbstractActionController { public function nlAction() {}

// www.example.com/nl/over-ons fails
$route = Http\Segment::factory(array(
  'route' => '/nl/over-ons',
  'defaults' => array(
    'controller' => 'Application\Controller\About',
    'action' => 'nl'
  ),
));
$router->addRoute('nlaboutus', $route, null);  

// it works - www.example.com/nl
$route = Http\Segment::factory(array(
  'route' => '/nl',
  'defaults' => array(
    'controller' => 'Application\Controller\Nlindex',
    'action' => 'index'
  ),
));
$router->addRoute('nlindex', $route, null); 

我认为您无法以这种方式处理语言环境。 如果你的应用是 nl only 那么构建你所有路由的前缀。

为此,您可以使用 module.php

中的 2 个触发器轻松完成
$eventManager->attach(
        MvcEvent::EVENT_ROUTE,
        array($this, 'setBaseUrl'),
        -100
    );

    // Trigger before 404s are rendered.
    $eventManager->attach(
        MvcEvent::EVENT_RENDER,
        array($this, 'setBaseUrl'),
        -1000
    );

其中 setBaseUrl 是一个方法

/**
 * Triggered after route matching to set the base URL for assembling with ProxyPass.
 *
 * @param \Zend\Mvc\MvcEvent $e
 */
public function setBaseUrl(MvcEvent $e)
{
    $router = $e->getApplication()->getServiceManager()->get('Router');
    $router->setBaseUrl('/nl');
}

如果不是refers to this question And this pull request

继续: 您可以在路线中添加语言环境。

您还可以将路由 /nl 设置为文字路由,将所有其他路由设置为 child_routes。要了解更多信息,请参阅 http://framework.zend.com/manual/current/en/modules/zend.mvc.routing.html

您可以使用普通路由配置并使用工厂来创建路由器。我认为在这种情况下您的配置将如下所示:

use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;

//...

$config = array(
    'routes' => array(
        'nlindex' => array(
            'type' => 'literal',
            'options' => array(
                'route' => '/',
                'defaults' => array(
                    'controller' => 'Application\Controller\NL\Index',
                    'action' => 'index'
                )
            )
            'may_terminate' => true,
            'child_routes' => array(
                'nlaboutus' => array(
                    'type' => 'literal',
                    'options' => array(
                        'route' => '/over-ons',
                        'defaults' => array(
                            'controller' => 'Application\Controller\About',
                            'action' => 'nl'
                        )
                    )
                )
            )
        )
    )
);

$router = HttpRouter::factory($config);