Answer the question
In order to leave comments, you need to log in
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
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.
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);
{{ object_path('route_name', entity) }}
All the necessary parameters will be taken from the model. Handy for CRUD
Please do not generate routes in the model! Generate routes where you use these models.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question