lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
Creating Custom Behaviors in CakePHP
The CakePHP manual leaves a lot to be desired on this topic. Here's one important tip that I couldn't find mentioned on the site:

Every method in your behavior class must have a reference to the model passed as its first argument.

Another tip:

If calling another method from within your behavior class, you must include the model reference as your first argument.

I've added a gratuitous example to the test method below.

A simple behavior class that can be used as a template:

<?php

class NormalizerBehavior extends ModelBehavior {

public $name = 'Normalizer';

/*
Initiate behaviour for the model using specified settings.
*/
function setup(&$Model, $settings = array())
{
}

/*
Run before a model is saved.
*/
function beforeSave(&$Model)
{
}


function normalize_date(&$Model, $date_str)
{
return date('Y-m-d', strtotime(trim($date_str)));
}


function test(&$Model)
{
$date = $this->normalize_date($Model, date('Y-m-d'));
printf('testing behavior %s for model %s on %s', __CLASS__, $Model->name, $date);
}
}

?>


If I discover any other noteworthy tips, I'll add them here.

Labels:

thoughtful, ty.
thanks for the excellent tip, was the exact problem I was having.