4

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the expression language in your service definition.

This example should do what you want:

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

It fetches the request service and then executes the getBaseUrl method.

You will need to add a second parameter in your WigetModel for the base URL.

3 Comments

Have you tried this? Accessing the request directly as a service seldom works as expected. It will definitely not work in S3.x. It might work using request_stack.
Yes, I created a simple Symfony 2.7 project with the OP's WidgetModel class and was able to inject just the base URL. Do you have a link to anything that shows the migration path for 3.x?
"In Symfony 3.0, we will fix the problem once and for all by removing the request service from the container." symfony.com/blog/new-in-symfony-2-4-the-request-stack. You can keep up with what is going on in Symfony here: symfony.com/blog
0

To complete the answer, in Symfony 3 you can use request_stack to get the base url using expressions languages (updated link) such as:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.