0
votes

I'm working on a Symfony2 project and am trying to figure out how to pass parameters from the route configuration to the controller. I know I can configure default values in the route configuration, and retrieve the values in the controller using the appropriate var name in the function declaration, but that isn't exactly what I want.

My use case is the following. I have a standard method in my controller that I want to access from 2 or 3 different routes. Depending on which route is being called, I want to "configure" the method differently. I can accomplish this in a few ways:

  1. In my controller, check the route name using `$this->container->get("request")->get("_route"), but that is ugly, and then I am hardcoded to the route name. Moves configuration to the controller, which should just be logic - not configuration.
  2. Create a base controller class, and subclass each method for my different routes. Each subclassed method would then have the necessary configuration within the method. Cleaner soln than #1, but still "heavy" in the sense of having multiple classes for a simple need and still pushes configuration data into the business logic.
  3. Put configuration data into the route configuration. In the controller, access the configuration data as required. Ideal solution, but don't know how.

I can use the route default array to specify my arguments, but then must make sure to use a regex to ensure that the params are not overridden at the URL level (security risk). This is functional, but still kinda cludgy and not a pretty hack.

I presume that there must a better way to do this, but I can't seem to figure it out. Is there a way to access the routing object from the controller, and access the different configuration parameters?

1
What sort of parameters are you trying to access? As you have probably noticed, controllers are really are not designed to access a route object. Maybe there is a fourth solution.Cerad
I'd like to be able to put in custom configuration parameters. For example, I'm trying to specify what kind of permissions the method can allow for a user object (ex: from one route, read-only, from another route, read/print, a third route read/edit, etc).Eric B.

1 Answers

0
votes

You can pull the actual route from the router service. Something like:

$routeName = $this->container->get("request")->get("_route");
$router = $this->container->get("router");
$route = $router->getRouteCollection()->get($routeName);

Not sure if this would be such a great design though. Consider passing a $configName to your controller method, adding a parameter with the same name in a config file then using getParameter to access it. That would eliminate the route stuff from the equation.

Something like:

zayso_arbiter_import:
    pattern:  /import
    defaults: { _controller: ZaysoArbiterBundle:Import:index, configName: 'someConfigName' }

public function importAction(Request $request, $configName)