Generate a link from a service

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_stack service (introduced in Symfony 2.4) instead of the request service/scope and use the shared setting (introduced in Symfony 2.8) instead of the prototype scope (read more about shared services).


For Symfony 4.x, it's much easier follow the instructions in this link Generating URLs in Services

You only need to inject UrlGeneratorInterface in your service, and then call generate('route_name') in order to retrieve the link.

// src/Service/SomeService.php
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    private $router;

    public function __construct(UrlGeneratorInterface $router)
    {
        $this->router = $router;
    }
    public function someMethod()
    {
        // ...

        // generate a URL with no route arguments
        $signUpPage = $this->router->generate('sign_up');
    }

    // ...
}