Alternative to the beforeAction() event

January 11th, 2010

I often see that when someone needs something executed on every page request before anything else is executed, they usually put it in the controller beforeAction() method. Things you might want executed on every page request might be, for example (so you know what I’m talking about):

  • Handling the layout
  • Cleaning all GET and POST parameters (I don’t like to do this but some people do)
  • Language handling

I’ve seen people do this with CakePHP as well as with Yii. I find that beforeAction() is actually not an optimal place to put this sort of code. Imagine you put code for all of the examples I gave above plus three more in the beforeAction() method. You might image that the beforeAction() method would become cluttered and hard to read. I prefer lower coupling than this. We want these scripts split up into logical places. And guess what? With Yii this is easy. Application Components!

Let me write an example. Lets say we need to figure out what layout to display to the user on each request. We would like to execute some logic for this before the controller action is called. We do not use beforeFilter(). We instead create an application component. An application component is simply a class that extends CApplicationComponent.

class LayoutHandler extends CApplicationComponent {
	public function init() {
		//Put code here.

Now everything in the init() method will be executed when this application component is instantiated. So now, we just need to get it to instantiate on every request, before the action is executed. This is done in the application configuration using the preload property.

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
	// The 'layoutHandler' component will pre-load
	// application components

Now there are two main things I have done here:

  1. Defined the LayoutHandler class as an application component in the components property
  2. Set the layoutHandler to preload with the preload property

You may find that this method is much more organized than simply stuffing code in CController::beforeAction(). It also leaves your code more modular.

Note that now you can even access the LayoutHandler class anywhere within your app via Yii::app()->layoutHandler. Not useful in this example, but this is often very handy.

Share and Enjoy:
  • Digg
  • Facebook
  • Google Bookmarks
  • Technorati
  • Reddit
  • RSS
  • Twitter

Categories: Yii

Tags: , Leave a comment

Comments Feed57 Comments

  1. bettor

    hi Jonah,

    I am messing around with Yii and was thinking to develop an affiliate section. Do you think extending the CApplicationComponen is a good start in terms to use it as a catch all to monitor if $_GET['affiliate_id'] has been passed to any of the pages? What are your thoughts on this?


  2. Jonah

    If you need to check $_GET['affiliate_id'] for every request, then yes, I believe an application component would be a good solution. Maybe an ‘Affiliate’ component?

  3. bettor

    yes, I am planning to develop an affiliate component and your post is very valuable and I will definitely take it into consideration. I reserve the right to ask you if I hit a bump on my way tho… :P

  4. Jonah

    Thanks :) i’ll be interested in hearing how it goes

  5. naser

    i just say tnx :-)

  6. Camac

    Nice tip, exactly what I was looking for!

  7. Matthias


  8. Walker


  9. Aurelio


  10. Shenna


  11. Glenna


  12. Cecil


  13. Roslyn


  14. Sophia


  15. Zachary


  16. Tanesha


  17. Delilah


  18. Louie


  19. Antoine


  20. Christoper


  21. Josefa


  22. Ericka


  23. Tamera


  24. Natalie


  25. Ramonita


  26. Yolanda


  27. Inez


  28. Eugene


  29. Leonard


  30. Ara


  31. Neil


  32. Tiffany


  33. Bernadette


  34. Ezra


  35. Sean


  36. Madison

    I think this is among the most important information for me.
    And i am glad reading your article. But wanna remark on few general things, The web site style is perfect, the articles is really
    great : D. Good job, cheers


    Our two specialists, Neil Parker and Dr Lee Sproats, have
    a huge wealth of experience in professional astronomy but are
    made use of to handling users of all capabilities from absolute newbies with to professionals.
    This can actually be tough in picking a telescope for a number
    of hundred dollars or perhaps thousands, prior to
    you even see it. A good idea is to stick to the attempted and checked telescope manufacturers.

  38. maxi skirt pattern pdf

    In case you are in search of one thing somewhat sexier, than a Vogue sample is the
    one you want. Just one word of warning, general
    Vogue patterns, even the easy and really straightforward ones,
    tend to be a bit of more challenging than the other massive three” sample companies.
    If you first start stitching check with this helpful translation guide: very easy = easy;
    straightforward = common; average = advanced; and superior = do not try.

    I like a great maxi skirt!

  39. Monique


  40. Danelle


  41. Alisa


  42. Onita


  43. Marcia


  44. Dyspraxic Chronicles » Blog Archive » closed captioning webex

    [...] you have any kind of inquiries concerning in which and the way to work with real time captioning services, you are able to email us with our [...]

  45. Dyspraxic Chronicles » Blog Archive » open graph caption

    [...] you have any queries pertaining to where and how to use australian open caption it, you can get hold of us at our internet [...]

  46. japanese written translation,entity translation field collection,german to english internet translator

    [...] case you have any inquiries concerning wherever as well as how to employ history of translation 20 century, you are able to contact us with our [...]

  47. Dyspraxic Chronicles » Blog Archive » captioning video windows movie maker

    [...] you have any thoughts regarding exactly where and how to use closed captioning job salary, you can speak to us at the [...]

  48. Dyspraxic Chronicles » Blog Archive » closed captioning youtube seo

    [...] you have any type of concerns relating to where and just how to use closed captioning time warner, you could contact us at the [...]

  49. closed captioning videos on youtube - What Sparked!

    [...] you enjoyed this post and you would certainly like to receive more info concerning closed captioning services san francisco kindly browse through the web [...]

  50. Lupe


  51. hack a facebook account free 2014

    We use various effective algorithm in the application which allows it to get access
    to any accounts.

  52. Amelie

    For a short period of period, the color of a selected number of bricks will be demonstrated on each amount.
    When you’re expected attempt to recall every
    brick’s color. FOR BEST RESULTS: Memory Examination is quite helpful, nevertheless it remains not boundless.
    To essentially boost your head, join the brain coaching
    company. I use Lumosity every-day, plus it functions.
    A Lumosity treatment requires about 15-minutes per day. It is
    a fruitful, pleasurable strategy to preserve your mind sharp.

  53. orlando hypnosis clinic

    Excellent article. Keep writing such kind of information on your page.

    Im really impressed by your blog.Hello there, You have done a great
    job. I will definitely digg it and in my opinion recommend to my friends.
    I’m confident they’ll be benefited from this web site.

  54. Orlando


  55. Catherine


  56. Lorene


  57. Mason


Leave a comment

Feed / Alternative to the beforeAction() event