When to use element() and when to requestAction()
Published on Mar 16, 2009 by Jamie MunroSeveral times a week it seems, someone at my office is asking, "Jamie, should I use $this->element() or $this->requestAction()?"
Every time they ask, I ask them back, "What do you need to do?"
There are a few simple ways to determine if using an element is better or a request action is better.
To begin, let's describe the difference.
A requestAction, performs the entire function in the controller you are calling. E.g. if you perform database queries and data manipulation, that all gets executed by CakePHP and then it renders the view for that function.
This is different from an element because with an element, CakePHP simply renders the content in the view.
So, with those in my mind, I bet you are already getting a good feel when to use which. Here are my rules of thumb for when to use requestAction():
- Do you require database access?
- Do you want to re-use an existing controller function?
- Are you doing anything else that should not be in a view?
If you answer yes to any of the above, use a requestAction() on the controller and function. If you answered no, you most likely want to use an element.
In case you found this article during a seach and looking for some examples, here you go. Below is an example of calling a requestAction:
The above statement will call the invite function inside the users controller. It passes "send" as the first input parameter and 35 as the second. Basically, the data you pass in is the exact same data you would pass through the URL.
To perform an element request you do the following:
$this->element('display_user', array('user' => $user));
The above statement will load the display_user.ctp file in app/views/elements and will pass in the variable $user to the element.
Until next time.