Cake PHP Admin Routing

First things first: KISS.

As a developer who (in the early stages of CakePHP’s development) constantly reinvented the wheel with features already available through the framework itself, I am now so cautious of doing so it’s almost an abhorrence rather than a discipline. However, I feel that this particular obvious solution to a problem is worth sharing:

The Problem

I've got an admin prefix set up in my Cake application and I have a custom layout that I want to use instead of the default layout. I don't really want to specify it in all the admin functions within each controller, is there a way to do it within app_controller.php?

Yes:

function beforeRender() {
 if(!empty($this->params['prefix']) && $this->params['prefix']=='admin') {
  $this->layoutPath = 'admin';
 }
}

It's really simple. $this->action is the current action—lower case underscore (eg. the_current_action)— as a string. For a single word prefixed route (admin, manage, moderate, etc.) it is easily searched. You could opt for $this->layout = 'admin_layout' if you like, but I find that using $this->layoutPath affords a bit of freedom in future should i want to have multiple admin layouts and then I can have a specific controller function line that doesn't need to worry about the beforeRender function overriding anything.

Comments