Need help?

I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.

Please feel free to use the form below to contact me.




Creating a pre-dispatch in Symfony (if you are coming from Zend)

If you're looking for a way to execute a bit of code before it actually runs the module/action, then you're in the right place. The first thing is that it's not actually called a preDispatch, as it is referred to in Zend. Having a Zend background myself, this got me a bit confused, as there was nothing linking the 2, when doing a search in Google.

The 2 main things we'll look at are the preExecute and the filters.

With the first it works on a per-module basis - so, you'd have to stick it in each module action. But if you're looking to do it for just 1 module, then this will work for you. Here's an example action:


class mymoduleActions extends sfActions
{
  public function preExecute()
  {
    // The code inserted here is executed at the beginning of each action call in this module
    ...
  }
 
  public function executeIndex()
  {
    ...
  }
}

And that's it - pretty easy huh?

Well what if you want a preExecute for all your modules, but you don't want to repeat code in every action? You could create a custom action, by extending sfActions, and add the global preExecute in there, then extend your custom action in all your actions - that's one way. Or we could just use the built in filters in Symfony - here's an example filter:


class stuffFilter extends sfFilter
{
  public function execute ($filterChain)
  {
    // Code to execute before the action execution
    ...
 
    // Execute next filter in the chain
    $filterChain->execute();
 
    // Code to execute after the action execution, before the rendering
    ...
  }
}

You're probably wondering where you put stuffFilter.class.php - you can stick it under apps/myapp/lib/stuffFilter.class.php

And the next thing you'd need to do, is edit your filters.yml file, which can be found here: apps/myapp/config/filters.yml, so that it knows to use your new filter.


rendering: ~
web_debug: ~
security:  ~

stuff:                 # Filters need a unique name
  class: stuffFilter

cache:     ~
common:    ~
flash:     ~
execution: ~

For more information about filters, you could just do a search in Google, or check out this guide on the symphony site:

http://www.symfony-project.org/book/1_0/06-Inside-the-Controller-Layer


jon | March 27, 2011 | Comments (1)

Comments

Stands back from the keyboard in amazement! Tnhaks!
Comment by Sanne - May 07, 2011 @ 1:09 pm

Name (required)
Email (will not be published) (required)
Website

captcha