问题
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.
回答1:
One option is to create your own base controller, and have all other controller extend it. Your base controller would override the render
function of the Controller
class from symfony framework
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BaseController extends Controller
{
// override render method
protected function render($template, $data)
{
$commonData = [];// get data from wherever you need
parent::render($template, $data + $commonData);
}
}
Then in your other controllers
class MyAnotherController extends BaseController
{
public function fooAction() {
// ...
return $this->render('BarBundle:Foo:foo.html.twig', array('foo' => 'Foo Data'));
}
}
回答2:
One of options
public function commonAction($type) {
// ...
return $this->render('BarBundle:Foo:'.$type.'.html.twig', array('data' => $this->getTheDataThatIsNeededInEveryAction()));
}
where $type
would be bar, foo or baz
来源:https://stackoverflow.com/questions/28692035/add-data-to-return-of-all-actions-in-a-symfony-controller