条件路由中的表达式语言 - 上下文中的服务

Expression Language in conditional routing - service in context

根据 docs,在条件路由中使用 expression language 时,默认情况下只有两件事可用 - contextrequest

我想使用 foo 服务和布尔 bar() 方法来确定条件。如何在这种情况下注入 foo 服务?

到目前为止我已经尝试过:

some_route:
    path: /xyz
    defaults: {_controller: "SomeController"}
    condition: "service('foo').bar()"

some_route:
    path: /xyz
    defaults: {_controller: "SomeController"}
    condition: "service('foo').bar() === true"

但我得到的是:

The function "service" does not exist around position 1.

P.s.: 我正在使用 Symfony 2.7.

最简单的方法是覆盖 context 变量,您可以通过装饰 router.request_context 服务来做到这一点。

services.xml:

<service id="router.request_context.decorated" class="Your\RequestContext" decorates="router.request_context" public="false">
        <argument>%router.request_context.base_url%</argument>
        <argument>GET</argument>
        <argument>%router.request_context.host%</argument>
        <argument>%router.request_context.scheme%</argument>
        <argument>%request_listener.http_port%</argument>
        <argument>%request_listener.https_port%</argument>
        <argument>/</argument>
        <argument type="string"/>
        <argument id="service_container" type="service"/>
</service>

请求上下文class:

use Symfony\Component\DependencyInjection\ContainerInterface;

class RequestContext extends \Symfony\Component\Routing\RequestContext
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct($baseUrl = '', $method = 'GET', $host = 'localhost', $scheme = 'http', $httpPort = 80, $httpsPort = 443, $path = '/', $queryString = '', ContainerInterface $container)
    {
        parent::__construct($baseUrl, $method, $host, $scheme, $httpPort, $httpsPort, $path, $queryString);
        $this->container = $container;
    }

    /**
     * @return mixed
     */
    public function service($service)
    {
        return $this->container->get($service);
    }
}

routing.yml:

some_route:
    path: /xyz
    defaults: {_controller: "SomeController"}
    condition: "context.service('foo').bar()"

此外,您可以创建表达式语言提供程序并注册 service 函数以简单地使用 service('foo') 而不是 context.service('foo') - 您需要添加此提供程序 运行 addExpressionLanguageProviderSymfony\Component\Routing\Router class.

荣格汉斯! :)