Expression Language in conditional routing - service in context

送分小仙女□ 提交于 2019-12-06 16:17:58

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! :)

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