H
H
HaruAtari2014-06-20 08:14:55
symfony
HaruAtari, 2014-06-20 08:14:55

Symfony 2.5: how to generate url in model?

Good afternoon.
Tell me, how can I generate a url string in the model method? In all examples, this is done in the controller. Google didn't turn up anything on my question. There was a solution, but it only worked on older versions of the framework.
Tell me how to get access to the router from the model?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pavel Solovyov, 2014-06-20
@HaruAtari

make the model a service (introduce a container or router), but I’ll say right away that this is the wrong approach to generate links in the model, etc., the model should only have the logic of working with the database.

B
BoShurik, 2014-06-25
@BoShurik

I solved it in two ways:
1. RoutableInterface with getRouteName and getRouteParameters methods. For twig, I wrote my own wrapper over path, which used these methods {{ object_path(entity) }}
2. My own route generator with code like this:

$compiledRoute = $route->compile();
$variables = $compiledRoute->getVariables();

$parameters = array();
if (!empty($variables)) {
    foreach ($variables as $variable) {
        $parameters[$variable] = $this->getObjectProperty($object, $variable);
    }
}

return $this->router->generate($name, $parameters);

As a result, I use as {{ object_path('route_name', entity) }}All the necessary parameters will be taken from the model. Handy for CRUD

F
faost, 2014-06-26
@faost

Please do not generate routes in the model! Generate routes where you use these models.

  • If it's a controller then $this->generateUrl()
  • In twig {{ path() }}
  • In the cost service, put a dependency on "router" or on the entire container (worse) and use $this->router->generate()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question