Happy cinco de mayo and 1 year anniversary

Well, what a lovely coincidence…

This blog turns 1 year old and there’s a good excuse to drink a few margaritas.
So, using this occasion I’d like to wholeheartedly thank the entire CakePHP team and the community for making my life so much easier and even a little more fun :)

Last year we celebrated CakePHP 1.2 stable and I have feeling that this year is going to be even more exciting with 1.3 being under energetic development.

… and I’ll certainly work to keep this blog going for another year or two ;)

God speed, and party on!

Execute code in model callbacks based on controller actions

I think it happens pretty often, that you need to run some code in a given model’s callback, but only on certain controller actions.

For example, we have a User model and it has an afterFind() method, which massages the results array in some manner. However, we only want for this to happen when our controller action is called “test”.

Well, it’s as easy as 1, 2, 3…

1. Add this to your App Model:


var $controllerAction = null;

function setControllerAction( $action = null ) {
    if($action) {
        $this->controllerAction = $action;
    }
}

2. Now in your User model, you can do something like this:


function afterFind($results, $primary = false) {
    if($this->controllerAction == 'test') {
        // run some code such as $this->_reformatTestData($results); 
    }
}

3. And this is how you would set things up in the controller:


$this->User->setControllerAction('test');
$this->User->find('all');

Done.