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 Feed200 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

  58. Bradly

    IQ

  59. Cara

    SH

  60. Ron

    HH

  61. Enrique

    FR

  62. Beth

    AZ

  63. Carson

    DM

  64. Dusty

    CA

  65. Sabrina

    QU

  66. Michaela

    NL

  67. Gaye

    WI

  68. Jorja

    IL

  69. Alphonse

    VT

  70. Vicki

    RT

  71. Liza

    PT

  72. Christian

    CV

  73. Nancy

    SF

  74. Reva

    HV

  75. Nelson

    JT

  76. Lisette

    IW

  77. Reece

    CA

  78. Senaida

    GU

  79. Darrell

    NN

  80. Christi

    YU

  81. Makayla

    VP

  82. Carlton

    TT

  83. Donnell

    MR

  84. Allan

    NS

  85. Chastity

    HX

  86. Krystal

    KT

  87. Letha

    NX

  88. Eusebia

    YG

  89. Angelo

    QZ

  90. Luca

    FF

  91. Malorie

    ON

  92. Jonathon

    PG

  93. Randolph

    WU

  94. Norma

    KQ

  95. Bonnie

    RJ

  96. Elvia

    ZT

  97. Shana

    VT

  98. Eleanore

    GR

  99. Grazyna

    ZQ

  100. Bridgette

    RU

  101. Kimberly

    ZE

  102. Zane

    It’s fantastic that you are getting ideas from this article as well as from our discussion made at this time.

  103. Lorena

    LS

  104. Christena

    RQ

  105. Shavonne

    OR

  106. Elida

    TU

  107. Celesta

    KV

  108. Merrill

    OG

  109. Cynthia

    AZ

  110. Jeffry

    VM

  111. Bess

    PX

  112. Genie

    DN

  113. Fidelia

    LU

  114. Dannielle

    LY

  115. Thao

    RP

  116. Paulina

    FM

  117. Gino

    LD

  118. Susana

    PZ

  119. Trisha

    RQ

  120. Adrianna

    XB

  121. Fabian

    NM

  122. Almeda

    KL

  123. Ramiro

    KQ

  124. Michele

    DC

  125. mahjong games

    You ought to be a part of a contest for one of
    the best blogs on the web. I will recommend this web
    site!

  126. Boris

    NB

  127. Lucas

    LR

  128. Shawnee

    JH

  129. Dessie

    AQ

  130. Hortense

    YS

  131. Lance

    NX

  132. Britney

    EE

  133. Kina

    BP

  134. Cornelius

    EP

  135. Louise

    ZD

  136. Gladys

    VY

  137. Tandy

    VU

  138. Annetta

    JG

  139. Catherine

    XR

  140. Graig

    YD

  141. Byron

    XE

  142. Olivia

    JT

  143. Mallory

    ZT

  144. Felix

    HH

  145. b&q stair parts

    Remember that it’ll soon be belonging to others, so make an effort to that would be that who are only possible.
    Since mechanisms pose more problems as they age, you are able to expect that used stair
    lifts require more repairs and maintenance than new units.

    Apart from space, however, in addition, you need an acceptable electricity system.

  146. Marty

    WY

  147. Benjamin

    WP

  148. Shirleen

    LH

  149. Virgie

    TV

  150. Greta

    ST

  151. Yolanda

    BQ

  152. Tommie

    PX

  153. Janis

    QZ

  154. Indiana

    XC

  155. Eva

    QJ

  156. Percy

    NU

  157. Charmain

    ZG

  158. Tammi

    IB

  159. legal transcription business start up

    Every weekend i used to pay a visit this web page, because i want enjoyment, since this
    this web page conations actually pleasant funny material too.

  160. Fabian

    LW

  161. Caren

    IJ

  162. transcription termination in eukaryotes

    Yes! Finally someone writes about lynch.

  163. percent data

    Hi every one, here every one is sharing these kinds of know-how,
    so it’s pleasant to read this weblog, and I used to pay a visit this
    web site daily.

  164. video transcription services new york

    Thanks for any other informative site. The place else may just I get that
    type of information written in such a perfect method?
    I have a venture that I’m simply now operating on, and I have been
    on the look out for such info.

  165. transcriptionist dictionary

    Hello there I am so thrilled I found your website, I really found you by error,
    while I was looking on Yahoo for something
    else, Anyhow I am here now and would just like to say thank you for
    a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to read through it all
    at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great
    deal more, Please do keep up the excellent jo.

  166. certified audio transcription

    Asking questions are really pleasant thing if you are not understanding
    anything fully, except this paragraph presents good understanding even.

  167. transcriptionist las vegas

    It’s awesome to visit this web site and reading the views of all mates regarding this piece of writing,
    while I am also keen of getting knowledge.

  168. legal transcription business start up

    Very quickly this site will be famous amid all
    blog users, due to it’s pleasant posts

  169. transcription initiation

    Thanks for sharing your thoughts on cartoon. Regards

  170. transcriptionist training

    That is really interesting, You’re an excessively skilled blogger.
    I’ve joined your feed and look forward to searching for
    more of your wonderful post. Additionally, I have shared your website in my social
    networks

  171. transcription services pittsburgh

    This post will help the internet visitors for building up new web site or even a weblog from start to end.

  172. transcriptionist keyboard

    It’s remarkable in favor of me to have a website,
    which is valuable for my knowledge. thanks admin

  173. medical transcriptionist uk

    Yes! Finally something about atom.

  174. transcription services qualitative research

    What i do not realize is in reality how you’re not
    really much more neatly-favored than you may
    be right now. You are so intelligent. You recognize thus considerably relating to this matter, produced me for my part imagine it from numerous varied angles.
    Its like men and women are not interested except it is something to accomplish with Girl gaga!
    Your individual stuffs nice. Always deal with it
    up!

  175. audio transcription rates

    What’s up all, here every one is sharing these familiarity, thus it’s
    nice to read this blog, and I used to pay a visit this website all the time.

  176. transcription services uk jobs

    Just wish to say your article is as surprising.
    The clarity for your publish is just nice and that i can think you are an expert in
    this subject. Well along with your permission allow me to clutch
    your RSS feed to keep updated with forthcoming post.
    Thank you 1,000,000 and please continue the enjoyable work.

  177. legal transcription certification training

    What’s Going down i am new to this, I stumbled upon this
    I have discovered It positively useful and it has aided me out loads.
    I’m hoping to give a contribution & aid different customers like its aided me.

    Great job.

  178. transcriptionist hearing loss

    Highly descriptive blog, I loved that bit. Will there be a
    part 2?

  179. transcriptionist australia

    Great blog right here! Also your website rather a lot up fast!
    What host are you the usage of? Can I am getting your affiliate hyperlink
    in your host? I wish my site loaded up as fast as yours lol

  180. Alecia

    YO

  181. transcriptionist pictures

    Pretty section of content. I simply stumbled upon your website and in accession capital to claim that I acquire actually enjoyed account your weblog posts.
    Anyway I’ll be subscribing on your feeds and even I fulfillment you get admission to constantly rapidly.

  182. transcriptionist interview questions

    great points altogether, you simply gained a new reader.
    What may you suggest about your publish that you made some days ago?
    Any positive?

  183. transcriptionist training online

    We stumbled over here from a different web address and thought I might check things out.
    I like what I see so now i’m following you. Look
    forward to looking over your web page again.

  184. Arlette

    FD

  185. Alanna

    NW

  186. Teodoro

    LS

  187. transcription services los angeles ca

    Wonderful article! We are linking to this great article on our
    site. Keep up the good writing.

  188. legal transcription test

    Hi to every , for the reason that I am in fact keen of reading this website’s post
    to be updated regularly. It includes good material.

  189. transcriptionist omaha ne

    I’m really enjoying the theme/design of your website.
    Do you ever run into any internet browser compatibility issues?
    A couple of my blog visitors have complained about my blog not working
    correctly in Explorer but looks great in Opera. Do you
    have any solutions to help fix this issue?

  190. transcription services employment

    I read this paragraph completely concerning the comparison of hottest and previous technologies, it’s amazing article.

  191. transcriptionist pay rate

    You could definitely see your enthusiasm in the article you write.
    The sector hopes for even more passionate writers like you who
    aren’t afraid to mention how they believe. Always follow your heart.

  192. zf5 transcription factor

    Everyone loves what you guys tend to be up too. This sort of clever work and coverage!
    Keep up the wonderful works guys I’ve you guys to my own
    blogroll.

  193. transcription services phoenix

    I do accept as true with all of the concepts you have offered to your post.

    They’re really convincing and will definitely work.
    Still, the posts are too short for novices. May you please extend them a bit
    from subsequent time? Thanks for the post.

  194. legal transcription samples

    If you would like to take a good deal from this article
    then you have to apply these methods to
    your won website.

  195. transcription enhancer

    May I simply say what a comfort to uncover somebody that actually understands what they’re talking about over the
    internet. You actually know how to bring a problem to light
    and make it important. More people need to check this out and understand this side of the story.
    It’s surprising you are not more popular given that you certainly have
    the gift.

  196. transcription services milwaukee

    What’s up, I would like to subscribe for this web site to obtain most recent updates, thus where
    can i do it please help.

  197. court transcription courses

    you are in reality a excellent webmaster.
    The web site loading velocity is amazing. It kind of feels that you are doing any unique trick.
    Also, The contents are masterpiece. you have performed a wonderful job on this matter!

  198. Pauline

    KF

  199. Winifred

    ZO

  200. company directory sharepoint

    Email is okay, printed (if their economics justify it) is better.
    Today, especially during our challenging economic times, invoice factoring services can be a
    beneficial tool for business owners worldwide. ” To treat both of these groups the way you would want to be treated would be to lessen your effectiveness by at least 50%.

Leave a comment

Feed

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