问题
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