9

I know I can access current route name by $request->get('_route');.

If my route is defined this way:

/*
 * @Route("/get_by_category/{id}", defaults={"id" = 0}, name="get_products_by_category")
 */

How can I retrieve the id variable from within service?

4 Answers 4

17

You can get all route related parameters from the Request

$routeParams = $request->attributes->get('_route_params');
$id = $routeParams['id'];
Sign up to request clarification or add additional context in comments.

1 Comment

While it didn't work - $request->attributes->all() didn't return _route_params, it did suggest the solution. Thanks!
11

$request->attributes->get('id') does the trick.

Comments

3

You can do

/*
* @Route("/get_by_category/{id}", defaults={"id" = 0}, name="get_products_by_category")
*/
public function getProductsAction($id)
{
}

The $id variable will be available within the controller.

3 Comments

That is correct, assuming I want to access it from controller. I've edited the question - I wanted to access it from service.
@acid i think ti would be better to pass the id down into the service call, so that the service does not need to know about request - or where the id comes from at all.
And that the controller does know about the request data and handles it, as that's what a controller does. If the request data is bad controller should abort to view, not pass stuff down layers that shouldn't care about dealing with requests.
0

In Symfony 3.4, I just added function functionName(int $id) and the variable $id has defined in the function scope. My path was something/{id}. For multiple parameters like/{id}/that.{format} I just added the second parameter to the function: function functionName(int $id, string $format), and both of them are in the scope. Indeed, my functionName is a __invoke in a class used as controller to the route.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.