While developing large applications, we might wish to organize Controllers into Sub-Directories or Subfolders for our convenient. This article will guide you to smoothly organize the controllers in sub-directory or folder. I’m using Codeigniter version 3.0 here.
First of all create a sub-directory as you wish inside your application > controllers
directory and create a controller file in newly created subfolder as you usually do. For version 3.0, the controller class and file name must be appear as first letter with capital case. For example let’s say we have created a folder named ‘admin‘ and ‘Home.php‘ as default controller.
Specify routing rule to organize Controller into sub-directory
Now head to application > config > routes.php
and create a new rule to let codeigniter understand the URL and load the correct controller. So for our URL http://yourdomain.com/admin
write the following routing rule:
1 | $route['admin'] = "admin/home"; |
Now access the URL and page will show as whatever you have written in controller file to render view. But wait, what if you have functions & parameters in URL for admin? Let us specify few more rules to match with our controller functions:
1 2 3 4 5 6 7 8 9 10 11 | /* $route['subfolder/(:any)/(:any)/(:any)'] = "subfolder/controller/function/parameter"; */ // admin is our folder and home is our controller file (Home.php) there $route['admin/([a-z]+)/(:any)'] = "admin/home/$1/$2"; // http://yourdomain.com/admin/user/5 will map to 'user' function in 'home' controller with '5' as parameter $route['admin/([a-z]+)'] = "admin/home/$1"; // http://yourdomain.com/admin/users $route['admin'] = "admin/home"; |
I have written matching routing rules and explained above as well in the code. Please be careful about the orders of rules because once a rule is matched all the later rules (even if they are correct) are discarded. As you can see in code below:
1 2 3 4 5 6 7 8 9 10 11 12 | /* /controller/frontend/ (for webpages) /controller/manager/ (for controllers to manage cms) */ // WRONG ORDER $route['(:any)'] = "frontend/$1"; $route['manager/(:any)'] = "manager/$1"; // RIGHT ORDER $route['manager/(:any)'] = "manager/$1"; $route['(:any)'] = "frontend/$1"; |
You must have to give it a chance to match ‘manager’ before matching ‘any’. otherwise as per wrong order it will always hit ‘any‘ and redirect to ‘frontend’. It all about Organizing Codeigniter Controllers into Sub-Directories or Subfolders. Did you feel any difficulty or have any suggestion or ask something then comment below.