After learning CodeIgniter MVC framework architecture now we are going to learn about CodeIgniter Controller. In this tutorial, we will create a controller from scratch. Before getting started you need to remember that controller is a simple class which is controlling the flow of whole application with the help of the routing component.

Go to the controller folder within the application folder. Here you will found two files.

  • index.html – this is the default 404 error page.
  • Welcome.php – this is the default controller.

Create a new file having an extension of PHP. We are going to create a controller file with the name of “CodeigniterController.php”.

First, we will create a simple class in PHP having code as follows.

<?php 
class CodeigniterController{
}
?>

Note: Name of file must match with the name of class which you are creating for the controller.

Now we will extend our “CodeigniterController” class with CI_Controller.

<?php
class CodeigniterController extends CI_Controller{

}
?>

Now we will add some action listeners within CodeIgniter controller. Every action listener is just a public function which you can declare as follows.

<?php
class CodeigniterController extends CI_Controller{

public function index() {
echo "Welcome to TutorialPace.com";
}

public function page() {
echo "This is page action listener";
}

public function blog() {
echo "This is blog action listener";
}

}
?>

The index is the default action listener. If the user will call the only controller without any parameter after /then index action listener will execute automatically.

Default Action Listener
/index.php/CodeigniterController
Page action listener
/index.php/CodeigniterController/page
blog action listener
/index.php/CodeigniterController/blog