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.

<?php
class LayoutHandler extends CApplicationComponent {
 
	public function init() {
		parent::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.

<?php
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
 
	// The 'layoutHandler' component will pre-load
	'preload'=>array('layoutHandler'),
 
	// application components
	'components'=>array(
		'layoutHandler'=>array(
			'class'=>'path.to.LayoutHandler',
		),
	),
);

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
  • del.icio.us
  • 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?

    Cheers,
    b

  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

    VA

  8. Walker

    DH

  9. Aurelio

    PD

  10. Shenna

    BB

  11. Glenna

    XW

  12. Cecil

    ZF

  13. Roslyn

    SX

  14. Sophia

    WV

  15. Zachary

    WP

  16. Tanesha

    IK

  17. Delilah

    DU

  18. Louie

    IS

  19. Antoine

    YC

  20. Christoper

    UZ

  21. Josefa

    DM

  22. Ericka

    KK

  23. Tamera

    TL

  24. Natalie

    CY

  25. Ramonita

    QI

  26. Yolanda

    PA

  27. Inez

    OF

  28. Eugene

    GC

  29. Leonard

    XY

  30. Ara

    OW

  31. Neil

    BY

  32. Tiffany

    ER

  33. Bernadette

    JA

  34. Ezra

    WK

  35. Sean

    II

  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

  37. sportsseating.com

    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

    FQ

  40. Danelle

    LA

  41. Alisa

    NE

  42. Onita

    IJ

  43. Marcia

    EF

  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

    YZ

  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

    FX

  55. Catherine

    CE

  56. Lorene

    DT

  57. Mason

    MV

Leave a comment

Feed

http://php-thoughts.cubedwater.com / Alternative to the beforeAction() event