bakedproject.com Blog Not just another WordPress weblog

5Aug/100

CodeIgniter – organizing controllers into sub-folders a wild card _remap function

For a "hello world" project it is really not important, but building a CMS using the most amazing framework requires an organized "controllers" set. Implementing sub-folder for organizing controllers is probably the most efficient way to do this.

Here is an example...

I am writing a new "users" controller. The controller has following methods
login
logout
register
profile

So, instead of writing all these methods in the "users.php" controller file, I am going to create a "users" folder and create corresponding php files those methods. So my "users" folder directory tree going to look something like this
users
->login.php
->logout.php
->register.php
->profile.php

My controllers usually have "index" method, which is the default method for the controller. The URL 'http://yourdomain.com/users/profile' will reach the 'index' method. By default that is how the most amazing framework works. But, the URL 'http://yourdomain.com/users/profile/' will cause a 404 error! If we have a method called "view", 'http://yourdomain.com/users/profile/view/' is going to work, but for some reason, we may absolutely need the URL to be 'http://yourdomain.com/users/profile/'.

This is doable via the awesome "_remap" function!

For 'wild card' function matching,

function _remap($method) {
 if(method_exists ($this, $method)) {
  $this->$method();
  } else {
  $this->index();
 }
}