Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Controller variables to an EventListener in Symfony2?

I'm bored of writing this at the end of every action in Symfony2:

return $this->render('Project:Bundle:view.twig', array(
                                     'foo' => 1,
                                     'bar' => 2
                                 ));

So I've attempted to hook into the request lifecycle just after an action has been run, in order to save myself some typing. I want to be able to do something similar to this in my controller instead:

$this->params = array(
    'foo' => 1,
    'bar' => 2
);

A listener would then pass the params to the render, and auto-detect the template using the action name. I realise I need to use Event Listeners to achieve this, but I can't seem to hook into the lifecycle at the right time...

  • kernel.controller is good, because I can get at the controller, but it's before the action has been run, so $this->params won't be set
  • kernel.response is after the action has run, but I can't seem to get at the controller itself from here

FYI - I've got a Zend background, and this is (obv) my first time using Symfony2... If I'm approaching this problem in entirely the wrong manner, shout!

like image 495
Mathew Avatar asked Dec 03 '25 07:12

Mathew


1 Answers

If you're using the SensioFrameworkExtraBundle, you can use the @Template() annotation and return an array:

<?php

namespace Acme\FooBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class BarController
{
    /**
     * @Template()
     */
    public function bazAction()
    {
        return array(
            'some_value' => $someValue;
        );
    }
}

The annotation tells it to look for the view in the default location based on bundle, controller and action name (in this case, AcmeFooBundle:Bar:baz.html.twig).

like image 113
Derek Stobbe Avatar answered Dec 06 '25 02:12

Derek Stobbe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!