Before and After Actions

Ever wanted to run some functions or create some variables before every action in a module? Or ever wanted to do something crafty after every action and before the template gets displayed?

Even if your answer is no, its good to be aware for future projects, that Symfony is hiding some very valuable methods of doing such things. Read on…

For doing stuff before every action in your module, just create a new function called preExecute() like so:

class demomoduleActions extends sfActions
{
  public function preExecute()
  {
    // ... put your stuff here that you want to run before every Action ...
  }
}

Equally for doing anything you like after every action in your module just create a new function called postExecute() like so:

class demomoduleActions extends sfActions
{
  public function postExecute()
  {
    // ... put your stuff here that you want to run after every Action ...
  }
}

It really is as simple as that. I stumbled across a little while ago whilst working on a project for a client of mine. So I thought I’d share this with you all.

Cheers,
Rob

Written by Rob | Posted on April 18th, 2008 in symfony |

4 Comments to “Before and After Actions”

  1. Josh says:

    Never knew you could do postExecute() :).

  2. Rob (the author) says:

    Hi Josh,

    I must admit, i found it by accident, but it’s good to know ;-)

    Rob

  3. titang says:

    I worked with cakephp for long time. And now i am using symfony. Glad to see that symfony also has his beforeFilter and afterFilter.

  4. Matthew says:

    titang: note that preExecute() and postExecute() are NOT the same as Symfony filters.

    “$this->redirect(…);” or “return sfView::ERROR”, for example, will not work from within the pre or post methods of an action. To achieve this you need to use a Symfony filter chain.

Leave a Reply