Code snippets for symfony 1.x


[Symfony2] Extract the current namespace, bundle, controller and action name

Sometimes, you may have to know, at the controller level what are these informations, it can be easily achieved with the following regexp: (inside a controller action function)

$matches    = array();
$controller = $this->getRequest()->attributes->get('_controller');
preg_match('/(.*)\\\Bundle\\\(.*)\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);
$request = $this->getRequest();
$request->attributes->set('namespace',  $matches[1]);
$request->attributes->set('bundle',     $matches[2]);
$request->attributes->set('controller', $matches[3]);
$request->attributes->set('action',     $matches[4]);

These informations are now available in the action attributes:

For example:

echo 'namespace: '. $request->attributes->get('namespace'). PHP_EOL;
echo 'bundle: '. $request->attributes->get('bundle'). PHP_EOL;
echo 'controller: '. $request->attributes->get('controller'). PHP_EOL;
echo 'action: '. $request->attributes->get('action'). PHP_EOL;

Will output:

namespace: COil
bundle: ToolsBundle
controller: Home
action: index

See you. COil

PS: This can be useful in a preExecute() like function.

PS2: The namespace here is the parent directory where is stored the bundle.

by Loïc Vernet on 2012-03-17, tagged action  controller  preexecute  symfony2