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

时间:2015-09-04 12:59:51

标签: symfony routing

根据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。

1 个答案:

答案 0 :(得分:3)

最简单的方法是覆盖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>

RequestContext类:

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') - 您需要在{{{}上添加运行addExpressionLanguageProvider的提供程序1}} class。

Junger Hans! :)

相关问题