0

我有一个City存储在 cookie 中的参数。我想将其值作为模式前缀包含在我的路由配置中,如下所示:

# MyBundle/Resources/config/routing.yml

MyBundle_hotel:
    resource: "@MyBundle/Resources/config/routing/hotel.yml"
    prefix:   /%cityNameFromCookie%/hotel

我怎样才能做到这一点?

4

1 回答 1

2

给我们一个用例,说明您希望它如何工作,因为我没有看到困难。路由由您可以通过generateUrl函数、urltwig 函数或pathtwig 函数指定的参数组成。

在 Twig 中,您可以执行此操作

{{ path('MyBundle_hotel', {cityNameFromCookie: app.request.cookies.get('cityNameFromCookie')}) }}

在控制器动作中

$cookieValue = $this->get('request')->cookies->get('cityNameFromCookie');
$url = $this->generateUrl('MyBundle_hotel', array('cityNameFromCookie' => $cookieValue));

或从可以访问容器的任何地方

$cookieValue = $this->container->get('request')->cookies->get('cityNameFromCookie');
$url = $this->container->get('router')->generate('MyBundle_hotel', array('cityNameFromCookie' => $cookieValue));

在最后一个示例中,您可能想要更改访问容器的方式。

如果您担心它看起来有多复杂,您可以抽象这个逻辑并将其放在服务中或扩展router服务。

你可以在 Symfony 的文档中找到关于服务和服务容器的文档。

您还可以通过命令列出服务php app/console container:debug并找到router服务及其命名空间,从中您可以尝试找出如何扩展router服务(了解服务如何工作的非常好的方法)。

否则,这是创建服务的简单方法。

在您的 services.yml 中(在您的 Bundle 或 app/config/config.yml 中)

services:
    city:
        class: MyBundle\Service\CityService
        arguments: [@router, @request]

在你的CityService课上

namespace MyBundle\Service

class CityService
{

    protected $router;
    protected $request;

    public function __construct($router, $request) 
    {
        $this->router = $router;
        $this->request = $request;
    }

    public function generateUrl($routeName, $routeParams, $absoluteUrl)
    {
        $cookieValue = $this->request->cookies->get('cityNameFromCookie');

        $routeParams = array_merge($routeParams, array('cityNameFromCookie' => $cookieValue));

        return $this->router->generateUrl($routeName, $routeParams, $absoluteUrl);
    }
}

在您可以访问容器的任何地方,您都可以执行以下操作

$this->container->get('city')->generateUrl('yourroute', $params);

如果您仍然认为这不是一个很好的解决方案;您将不得不扩展路由器服务(或找到更好的方法来扩展路由器组件以使其行为符合您的预期)。

我个人使用上面的方法,所以我可以将实体传递给pathTwig 中的方法。您可以在services.yml中定义的MainServicePathExtension Twig 类中找到一个示例。

在 Twig 中,我可以做到forum_path('routename', ForumEntity),在容器感知环境中,我可以做到$this->container->get('cornichon.forum')->forumPath('routename', ForumEntity)

您应该有足够的信息来做出明智的决定

于 2013-03-25T21:38:11.493 回答