A behavior is where you extract code that doesn't really belong in one specific models domain. Kind of like, helper functions, or a mixin/module (if you're familiar with that pattern from other programming languages).
If you're familiar with CakePHP helpers and components, you can look at it like this. A behavior is to Model as Helper is to View as Component is to Controller. Basically a set of functionality that will be used across multiple models.
Let's say you want to implement soft delete on all the models in your application. (Soft delete meaning, you don't actually delete the record, you just mark it as deleted). You wouldn't want to put the same soft delete code into every model. That's not very DRY! Instead you use a behavior to abstract out the functionality like so.
What we're trying to do is instead of delete the record, update the deleted on column with the current date (it will work the same way as created, modified). Then we'll change the find method to only retrieve records that aren't deleted.
// models/behaviors/soft_deletable.php
class SoftDeletableBehavior extends ModelBehavior {
function setup(&$Model, $settings = array()) {
// do any setup here
}
// override the delete function (behavior methods that override model methods take precedence)
function delete(&$Model, $id = null) {
$Model->id = $id;
// save the deleted field with current date-time
if ($Model->saveField('deleted', date('Y-m-d H:i:s'))) {
return true;
}
return false;
}
function beforeFind(&$Model, $query) {
// only include records that have null deleted columns
$query['conditions']["{$Model->alias}.deleted <>"] = '';
return $query;
}
}
Then in your model
Class User extends AppModel {
public $actsAs = array('SoftDeletable');
}
And from your controller, you can call all of our behavior methods on your model
Class UsersControllers extends AppController {
function someFunction() {
$this->User->delete(1); // soft deletes user with id of 1
$this->User->find('all'); // this will not exclude user with an id of 1
}
}
I hope this helps you.