CakePHP get controller from model

As much as MVC is great, sometimes there’s that little requirement that forces you to go against the standard way of doing things.

In this case, my colleague Sam was writing a beforeSave method in his AppModel. It needed to check if some conditions were true (can’t really disclose what they are - but something to do with dates). If these conditions failed, we wanted to redirect the user and set a session flash message saying something scary like “ACCESS DENIED”.

The MVC person in me would have said that you shouldn’t be doing this from a model, but having the flash and redirect code in the controller would have sort of defeated the point of generifying the code into the AppModel.

For future reference, here’s how you go about getting access to a controller from a model.

App::import('Controller', 'App');
$appController  = new AppController();
$appController->constructClasses();

Of course you can do this with any other model to get a specific instance. The “constructClasses()” line makes sure that all the controller’s components and models are loaded in for you to access. So in our case, we could then do…

$appController->Session->setFlash('ACCESS DENIED');
$appController->redirect($somewhere);