最简单的方法是覆盖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') - 您需要在Symfony\Component\Routing\Router 类上添加运行addExpressionLanguageProvider 的此提供程序。
容格汉斯! :)