zen of coding

You gotta love… Bindable behavior

Update: as of 05/18/2008 there is a new core Containable behavior, which is an evolution of a few previous behaviors, including Bindable. If you are just looking into starting to use this behavior I suggest you go with the Containable, since it’s going to be the new standard in the CakePHP core. However, the examples on Containable are still scarce, so it’s a good idea to familiarize yourself with the way Bindable works. They share many similarities in syntax and overall approach.

If you haven’t started using Bindable behavior yet, I suggest you drop everything and get started on it right away. http://bakery.cakephp.org/articles/view/bindable-behavior-control-your-model-bindings

I promise, it will make your life much easier. The best part is that it is completely unobtrusive. You’ll probably have to go back and remove those bindModel/unbindModel calls you have in your code to make it lighter and prettier, but overall no changes to existing code are required.

Here’s a little example on how bindable can easily allow you to fetch Model data with somewhat complex conditions.

Example models:
User – has many Profiles
User – has many Tasks

My goal is to retrieve an active profile information (is_active =1 in the DB) for a given User. While at it, I’m also going to grab the Tasks.

It couldn’t be easier using bindable (Assuming that $id variable is defined or passed to the action):

[sourcecode language=’php’]
User->find(‘all’, array(‘conditions’=>array(‘User.id’=>$id),
‘restrict’ => array(‘Task’, ‘Profile’ => array(‘conditions’ => array(‘Profile.is_active’=>1)))));
?>
[/cc]

Of course more details and examples on how to use bindable can be found at the above article in the Bakery.

%d bloggers like this: