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

时间:2015-11-30 13:14:55

标签: php zend-framework zend-framework2

我正在尝试我的路由工作,但它无法正确路由。

当我要去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); 

3 个答案:

答案 0 :(得分:1)

我不认为你可以这样处理语言环境。 如果您的应用仅为nl,则构建所有路线的前缀。

为此,您可以使用module.php中的2个触发器轻松完成此操作

/**
 * 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');
}

其中setBaseUrl是方法

admin.py

如果不是refers to this questionthis pull request

要恢复: 您可以在路线中添加区域设置。

答案 1 :(得分:1)

您还可以将route / nl设置为Literal路由,将所有其他路由设置为child_routes。要了解详情,请参阅http://framework.zend.com/manual/current/en/modules/zend.mvc.routing.html

答案 2 :(得分:1)

您可以使用普通路由配置并使用工厂来创建路由器。我认为在这种情况下你的配置看起来像这样:

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);