Welcome to the Cookbook

loading...

3.8.2 Creating Behaviors

Behaviors that are attached to Models get their callbacks called automatically. The callbacks are similar to those found in Models: beforeFind, afterFind, beforeSave, afterSave, beforeDelete, afterDelete and onError - see Callback Methods.

Your behaviors should be placed in app/models/behaviors. It's often helpful to use a core behavior as a template when creating your own. Find them in cake/libs/model/behaviors/.

For example a Slugable behaviour should be placed in app/models/behaviors/slugable.php and look like this:

class SlugableBehavior extends ModelBehavior {
    function setup(&$Model, $settings) {
        // do something when creating behaviour object
    }
}
  1. class SlugableBehavior extends ModelBehavior {
  2. function setup(&$Model, $settings) {
  3. // do something when creating behaviour object
  4. }
  5. }
Setup is called when the Behaviour is created. You can pass in variables to use them. See below. Every Method you create in your Behaviour should take a reference of the model as first parameter. See creating behaviour methods section.

Every callback takes a reference to the model it is being called from as the first parameter.

Besides implementing the callbacks, you can add settings per behavior and/or model behavior attachment. Information about specifying settings can be found in the chapters about core behaviors and their configuration.

A quick example that illustrates how behavior settings can be passed from the model to the behavior:

class Post extends AppModel {
	var $name = 'Post'
	var $actsAs = array(
		'YourBehavior' => array(
			'option1_key' => 'option1_value'));
}
  1. class Post extends AppModel {
  2. var $name = 'Post'
  3. var $actsAs = array(
  4. 'YourBehavior' => array(
  5. 'option1_key' => 'option1_value'));
  6. }

As of 1.2.8004, CakePHP adds those settings once per model/alias only. To keep your behavior upgradable you should respect aliases (or models).

An upgrade-friendly function setup would look something like this:

function setup(&$Model, $settings) {
	if (!isset($this->settings[$Model->alias])) {
		$this->settings[$Model->alias] = array(
			'option1_key' => 'option1_default_value',
			'option2_key' => 'option2_default_value',
			'option3_key' => 'option3_default_value',
		);
	}
	$this->settings[$Model->alias] = array_merge(
		$this->settings[$Model->alias], (array)$settings);
}
  1. function setup(&$Model, $settings) {
  2. if (!isset($this->settings[$Model->alias])) {
  3. $this->settings[$Model->alias] = array(
  4. 'option1_key' => 'option1_default_value',
  5. 'option2_key' => 'option2_default_value',
  6. 'option3_key' => 'option3_default_value',
  7. );
  8. }
  9. $this->settings[$Model->alias] = array_merge(
  10. $this->settings[$Model->alias], (array)$settings);
  11. }