Expression Language in conditional routing - service in context

时间秒杀一切 提交于 2019-12-08 05:36:07

问题


According to docs, there are only two things available by default, while using expression language in conditional routes - context and request.

I would like to use foo service with boolean bar() method to determine condition. How to inject foo service into this condition?

So far I've tried:

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

and

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

but all I get is:

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

P.s.: I'm using Symfony 2.7.


回答1:


Easiest way is to override context variable, you can do that by decorating router.request_context service.

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 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()"

Additionally, you can create expression language provider and register service function to simply use service('foo') instead of context.service('foo') - you need to add this provider running addExpressionLanguageProvider on Symfony\Component\Routing\Router class.

Junger Hans! :)



来源:https://stackoverflow.com/questions/32398724/expression-language-in-conditional-routing-service-in-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!