requestAction considered harmful
Posted by Felix Geisendörfer, 5 hours, 31 minutes ago - in Controllers, Components & Shells
Hey folks,
this is post #1 of my 30 day challenge. If you have ever written a modestly complex application in CakePHP, you probably noticed that it is very tempting to use requestAction to glue together pieces from different controller actions. While initially that sounds like a good idea, I think requestAction should be avoided wherever possible.
Avoid requestAction in your application wherever you can - it will save you from terrible debugging nightmares.
For one, the speed penalty of using requestAction is quite prohibitive. The main slowdown is that every time you call requestAction, a full dispatch cycle takes place. This is pretty inefficient given that you probably already know what exact Controller/action you want to call up. A much bigger reason is that you will create a debugging nightmare for yourself. As soon has you have requestAction calls that invoke requestAction calls that invoke requestAction calls - you're screwed. If somewhere along the chain odd things happen (like a bug in your Auth system, some controller's / component's beforeFilter) debugging is going to become a major pain.
But worry not. This doesn't mean that you have to overload your dashboard / profile pages with ridiculous amounts of logic. The approach to use is to create named find calls and move all logic there. Once you have done that, getting the data for a complex view is simply a matter of making the right find calls and rendering a bunch of elements. You can even render other controllers views where it makes sense. For example lets say you want to re-use posts/view.ctp inside posts/edit.ctp to show the user a preview of the currently edited post. Instead of using requestAction, try this:
Again, there are some legitimate cases for using requestAction. All I'm saying here is that you should avoid creating an architecture that depends on requestAction at all costs. I've seen (and rewritten) applications that have gone that route and it has never been pretty so far ; ).
HTH,
-- Felix Geisendörfer aka the_undefined



klevo: Glad you like the post : ). About the title: english is my second language so I might be...
Very good post, especially the solutions to avoid using requestAction. But the title may be a...
Daniel Hofstetter: I'm experimenting with different checks & balances strategies for different...
Wouldn't it be more effective to use a strategy not based on "punishment"? At least for me it is...
Damn, so I gotta get up early now if I want to earn money, heh? But seriously: Good luck for...