Grouping controllers without using modules

Basic Yii application’s route consists of controller and action. Sometimes you have to add an extra separation layer, to group controllers and actions belonging to separate groups. Not everyone know, that you don’t have to use modules for this purpose. Controllers subdirectory can also be a considerable option. For me, this was a nifty discovery, so I decided to write this down as a personal memo.

The simpilest route have only controller and action part (and of course additional parameters, passed to action, if necessary). For example:

http://localhost/main/show.html?page=intro

Here we have main controller, show action and page parameter with intro value passed to that action.

Many times you have to separate group of controllers handling some functionallity in your application from another group. The most obvious example is to separate frontend (standard) controllers from administration panel’s one. Another example could be a job portal, with spearation of job seekers and employers sections.

First think that can come to a mind is: use modules. Let’s keep frontend controllers in default place and let’s move administration panel’s ones to admin module.

But the truth is, that you should hire modules only, if you really need them. A module is actually whole Yii application embeded inside main application. You don’t always need it. For a simple separation, just to keep order in your directories and URLs, you can put controllers into spearate subdirectiores.

Take a look at CWebApplication.createController method. It says, that if first two attempts of creating controller instance (using controllerMap and a module ID) fail, Yii will attempt to search it under controllerPath. And an example. If the route is admin/user/create, the controller will be created using the class file protected/controllers/admin/UserController.php.

Leave a Reply