Behavior is where you retrieve code that really does not belong to the same model domain. For example, helper functions or mixin / module (if you are familiar with this template from other programming languages).
If you are familiar with CakePHP helpers and components, you can look at it this way. The behavior is in the model, since the assistant should be considered as a component for the controller. Basically a set of functionality that will be used for several models.
Suppose you want to implement soft deletion on all models of your application. (The soft value is delete, you are not actually deleting the record, you just mark it as deleted). You would not want to enter the same soft delete code in each model. This is not very DRY! Instead, you use behavior to abstract away from such functions.
What we are trying to do is not delete the record, update the deleted column with the current date (it will work the same as the created, modified). Then we modify the find method to retrieve only those records that are not 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('Ymd 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 our behavior methods on your model.
Class UsersControllers extends AppController { function someFunction() { $this->User->delete(1);
Hope this helps you.
source share