Search code examples
symfonyservicedependency-injectionbase-url

Getting Symfony base URL from a service?


I have a service that needs to access the current application base URL (what's returned by app.request.getBaseURL() in Twig views). Currently, my config is like this:

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

So as a second argument, I would like to inject the base URL. Is it possible? If not, what would be proper solution?


Solution

  • As far as I know there is no builtin base url service. Which is actually a bit of a red flag that maybe having your component depending on it might not be such a good idea. But I can't think of a good reason why.

    So normally, one would just inject the request object. But that has it's own problems as documented here: http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

    Instead, inject the @request_stack service and pull the url from it:

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

    If you do find yourself needing the baseUrl in multiple services then you could define your own factory type service to generate it. But again, that might mean your design needs rethinking.