0

Is there a recommended way of choosing how to give data to a controller?

Often I have to decide if I want to use route place holders like:

/**
 * @Route("/hello/{name}", name="hello")
 */
public function indexAction($name)
{
    return new Response('<html><body>Hello '.$name.'!</body></html>');
}

Usage: /hallo/Thorsten

Or use query parameters ($_GET):

/**
 * @Route("/hello")
 */
public function indexAction()
{
    $request = Request::createFromGlobals();
    $name = $request->get('name');
    return new Response('<html><body>Hello '.$name.'!</body></html>');
}

Usage: /hallo?name=Thorsten

Marcel Pfeiffer
  • 878
  • 7
  • 11
  • 3
    See http://stackoverflow.com/a/4028874/711206 – Federkun May 27 '15 at 08:19
  • 6
    Side-question: Why are you creating the request-object inside the controller? You should normally use `indexAction(Request $request, ...)`, where symfony will inject the current request. – Yoshi May 27 '15 at 08:22
  • Difference between those two is that you have to check if the value exists etc. inside the controller for the second example. In the first you have to make sure you have all the parameters when generating the url/path. I myself prefer the first one because it's easier to not lose yourself in routes.. Also you can create more than one route for one Action, just with different parameters – Koalabaerchen May 27 '15 at 08:30

1 Answers1

1

I don't think there is a rule for this, it depends.

Is the value a generic string possibly containing spaces or weird characters or symbols or maybe slashes? I'd use the query string, it's widely used for searches, pagination and such.

Is the value in a set of predefined "words" or "numbers", like categories, user IDs, blog post slugs and such? I'd use the path for simplicity and to follow SEO rules.

Take a look here for more information on what I mean: http://googlewebmastercentral.blogspot.co.nz/2015/04/better-presentation-of-urls-in-search.html

ggioffreda
  • 575
  • 5
  • 8