Monday, January 10, 2011

Organise controllers in Codeigniter using subfolders

This is my extended guide to using folders in Codeigniter. There are a couple of guides out there, but I thought a more detailed with step by step guides.

In this instance I will be creating a very common controller named 'Admin' with a basic controller named 'login' within a folder named 'secure' - its URI will look like this:

http://www.domain.com/secure/admin/login

First, go to your 'Controllers' Folder
Then add a folder named 'secure' - this will contain your new set of controllers.
We then create a file within the new folder named 'admin.php' - the new controller file

Declare your subclass:

<?php
class admin extends Controller {

function __construct() {
parent::Controller();
}

function login() {
//your code to go here
}

}
?>

Adding a default

When you add a controller folder, you can also add in the default controller to run should the person viewing the site not enter a controller name, for example:

http://www.domain.com/secure/

You add the default like so:

Create a new file and name it the same as your default controller name in 'routes.php', the default controller in Codeigniter is 'welcome', so that is what we will create:

controllers/secure/welcome.php

We then need to create the code for this file:

class welcome extends Controller {

function __construct() {
parent::Controller();
}

function index() {
//your code to go here
}

}

For more information on Codeigniter and how Controllers work within go to:http://codeigniter.com/user_guide/general/controllers.html

Labels: , , ,