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.

Related Posts

%d bloggers like this: