Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generateUrl outside controller

Tags:

symfony

Is there a possibility to use generateUrl() method outside of controllers?

I tried to use it in a custom repository class with $this->get('router'), but it didn't work.

update

I've found a temporary solution here:

http://www.phamviet.net/2012/12/09/symfony-2-inject-service-as-dependency-in-to-repository/

I injected the whole service container into my repository, although it's "not recommended".

But it works for now.

update2

Injecting router instead of the whole container is probably a better idea :)

like image 302
Sergejs Rižovs Avatar asked Mar 17 '13 07:03

Sergejs Rižovs


3 Answers

Don't inject the container into your repository... Really, don't !

If I were you, I would create a service and injects the router in it. In this service, I would create a method, that uses the repository and adds the needed code using the router.

That's way less dirty and easy to use/understand for another developer.

like image 108
Gmajoulet Avatar answered Nov 13 '22 12:11

Gmajoulet


If you take a look in the source code of Controller::generateUrl(), you see how it's done:

$this->container->get('router')->generate($route, $parameters, $referenceType);

Basically you just enter the name of the route ($route here); if exists, some parameters ($parameters) and the type of reference (one of the constants of the UrlGeneratorInterface)

like image 17
Wouter J Avatar answered Nov 13 '22 14:11

Wouter J


Inject the router itself into your EntityRepsitory (like described on Development Life blog's post Symfony 2: Injecting service as dependency into doctrine repository), then you can use $this->router->generate('acme_route');

like image 2
r1pp3rj4ck Avatar answered Nov 13 '22 14:11

r1pp3rj4ck