How can I generate a link from a service? I've injected "router" inside my service, however generated links are /view/42 instead of /app_dev.php/view/42. How can I solve this?
My code is something like this:
services.yml
services: myservice: class: My\MyBundle\MyService arguments: [ @router ] MyService.php
<?php namespace My\MyBundle; class MyService { public function __construct($router) { // of course, the die is an example die($router->generate('BackoffUserBundle.Profile.edit')); } }
So : you will need two things.
First of all, you will have to have a dependency on @router (to get generate()).
Secondly, you must set the scope of your service to "request" (I've missed that). http://symfony.com/doc/current/cookbook/service_container/scopes.html
Your services.yml becomes:
services: myservice: class: My\MyBundle\MyService arguments: [ @router ] scope: request Now you can use the @router service's generator function !
Important note regarding Symfony 3.x: As the doc says,
The "container scopes" concept explained in this article has been deprecated in Symfony 2.8 and it will be removed in Symfony 3.0.
Use the
request_stackservice (introduced in Symfony 2.4) instead of therequestservice/scope and use thesharedsetting (introduced in Symfony 2.8) instead of theprototypescope (read more about shared services).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With