CodeIgniter and Controllers structure

Posted by Luke | CodeIgniter, PHP, Programming, Web development | Monday 20 October 2008 4:58 pm

Over the weekend I was playing around with CodeIgniter. I was up and running pretty quickly and it all seemed to go pretty smoothly. Having built web applications and web sites for a number of years now and before that desktop applications etc, I’m usually pretty quick with establishing a technical structure for my site. I do this because I tend to work in iterations rather than focusing on one specific thing before moving on the next. Anyway, I became a bit frustrated when I noticed that I couldn’t subdivide my controllers folder. It seemed that I could only have one big pool of controllers. This was no good. I checked the documentation and at first I didn’t notice the section that describes how to divide your controllers folder into sub folders. When I finally had figured it out I ran into the next problem.

My site has a top level menu option called ‘Settings’. When you click ‘Settings’ I want to execute the ’settings’ controller located in the controllers/ folder. The Settings page however has more sub-options like Users, Groups, Roles etc. and I want all these controllers to live inside a settings/ folder that’s located in the controllers/ folder:

+ controllers/
   +settings/
      -users.php
      -groups.php
      -roles.php
   -settings.php

This was going to clash. Going to the localhost/myapp/settings URL would execute the ’settings’ controller and going to localhost/myapp/settings/users would bring up a 404 error page. I assume this is because the framework tries to execute a method called ‘users’ inside the ’settings’ controller.

Going back and forth with this issue I finally figured out a way to overcome this problem. In the routes.php configuration file you can set a default controller to execute. I’ve set mine to ‘index’. So, this could mean that if I would bring my settings.php file holder the Settings controller into the settings/ folder and rename it to index.php, it might execute that controller when browsing to localhost/mysite/settings. And behold, it does. the structure I ended up with was:

+ controllers/
   +settings/
      -index.php  <- default controller
      -users.php
      -groups.php
      -roles.php

I haven’t tried this yet with deeper structures but I assume that the same idea applies to that as well.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment