I have a controller in a Symfony 2.1 application, let's just call it FooController
in the BarBundle
. This controller has a lot of actions fooAction
, barAction
, bazAction
and a few more.
All of them have something in common. They're displaying in some part's the same data in the view, not in all, so I can't just use one action with the type as parameter. I would like to add the data that has to be passed to the view in one central place, otherwise, it just wouldn't be dry.
Bad (in my opinion):
public function fooAction() {
// ...
return $this->render('BarBundle:Foo:foo.html.twig', array('foo' => 'Foo Data', 'data' => $this->getTheDataThatIsNeededInEveryAction()));
}
public function barAction() {
// ...
return $this->render('BarBundle:Foo:bar.html.twig', array('bar' => 'Bar Data', 'data' => $this->getTheDataThatIsNeededInEveryAction()));
}
public function bazAction() {
// ...
return $this->render('BarBundle:Foo:baz.html.twig', array('baz' => 'Baz Data', 'data' => $this->getTheDataThatIsNeededInEveryAction()));
}
What I'm wondering now, is, what would be the "Good" way? Is there like a finished
function in the parent controller that is called just before sending the data to the view, where I could add that data to the response object?
Another possibility would be, to create an event listener, but I think that would be a waste of resources.
A third option would be to use the render function like {% render url('latest_articles', { 'max': 3 }) %}
I know nowadays it's {{ render(controller(..)) }}
but I'm stuck with Symfony 2.1 in with this project.