从服务获取 Symfony 基础 URL?

Getting Symfony base URL from a service?

我有一项服务需要访问当前应用程序库 URL(app.request.getBaseURL() 在 Twig 视图中返回的内容)。目前,我的配置是这样的:

services:
    WidgetModel:
        class: AppBundle\Model\WidgetModel
        scope: prototype
        arguments: ['%widgets%']

因此,作为第二个参数,我想注入基数 URL。可能吗?如果不是,什么是正确的解决方案?

据我所知,没有内置的基础 url 服务。这实际上是一个危险信号,让您的组件依赖于它可能不是一个好主意。但是我想不出一个很好的理由。

所以通常情况下,只需注入请求对象即可。但这有其自身的问题,如此处所述:http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

相反,注入 @request_stack 服务并从中提取 url:

class WidgetModel
{
  public __construct($widgets,$requestStack)
  {
    $this->baseUrl = $requestStack->getCurrentRequest()->getBaseUrl();

如果您确实发现自己在多个服务中需要 baseUrl,那么您可以定义自己的工厂类型服务来生成它。但同样,这可能意味着您的设计需要重新考虑。

您可以在服务定义中使用 expression language

这个例子应该做你想要的:

services:
    WidgetModel:
        class: AppBundle\Model\WidgetModel
        scope: prototype
        arguments: [%widgets%, "@=service('request').getBaseUrl()"]

获取请求服务,然后执行getBaseUrl方法。

您需要在 WigetModel 中为基础 URL 添加第二个参数。

要完成答案,在 Symfony 3 中,您可以使用 request_stack 使用 expressions languages (updated link) 获取基数 url,例如:

services:
    WidgetModel:
        class: AppBundle\Model\WidgetModel
        scope: prototype
        arguments: [%widgets%,"@=service('request_stack').getCurrentRequest().getBaseUrl()"