Controllers are the core of your application because they determine how HTTP requests should be handled. Let's dive right in and create a simple Hello World controller. Create a file called helloworld.php
in system/application/controllers/
.
<?php class Helloworld extends Controller { function HelloWorld() { parent::Controller(); } function index() { echo("Hello, World!"); } } ?>
Let's dissect this controller to get a better understanding of controllers.
Firstly, you can see that the controller is a class that extends the base Controller class. The next thing to note is that there is a function with the name index
. This is the default function, and will be called when another function has not been called. To see this being run, simply navigate to the URL http://yourwebsite.ext/index.php/helloworld/
and you should see the words Hello, World! on the screen.
All Controller class names should start with an uppercase letter, and the rest of the name should be lowercase. Controllers should always extend the base class so that you can use all of CodeIgniter's syntax and have access to all CI resources.
If you have a constructor in your Controller then you need to call upon the Controller
constructor, as we have in the example HelloWorld Controller. You should call it as follows:
Parent::Controller();
CodeIgniter has the ability to set a Controller as the default controller. This is the controller that is to be called when no other controller is passed to index.php
. A default CodeIgniter install will set the default controller to welcome_message.php
– this is the default CI welcome page, as shown earlier.
To set a different default controller, open the file system/application/config/routes.php
and change welcome
to the name of any other controller in your application.
$route['default_controller'] = "welcome";
You can remap function calls by using a function in your controller called _remap()
—this will be called every time that the controller is called, even if a different function is used. This is useful for developers who wish to easily remap their function calls in order to provide a different Uniform
Resource Identifier (URI) structure, or to remap functions instead of extending CodeIgniter's routing class.
The function string will be passed to the function. You would usually have a function that looks like this:
Function _remap($method) { if($method == "method_name") { $this->$method(); } else { $this->default_method(); } }