Codeigniter controller

Home > Codeigniter Tutorial > Codeigniter controller



Controller

The controller implements the logical implementation for writing the programme and creating the webpage. The controller serves as an intermediary between the model and the view. The Controller Controls Model as well as view.

Creating a Controller

Controller always stored inside Application/controllers folder. Condeigniter provides two basic files that is stored inside Application/controllers folder index.html and Welcome.php.
Keep these files as they are don't delete these files. Now Create a new file under the same path(Application/controllers) named "Hello.php"

<?php 
   class Hello extends CI_Controller
   {  
      public function index() 
	  { 
         echo "Hello World"; 
      } 
   } 
?>

Save Hello class inside Application/controllers/Hello.php. Here, Hello class inherit an in-built Codeigniter Class CI_Controller.

Points to Remember

Calling a Controller

  • CI_Controller class must be extended Whenever u want to create Your own Controller.
  • Controller name must be Started with Capital letter
  • Controller name and file name must be Similar
  • Syntax
    http://localhost/index.php/controller-name/method-name
    

    Open Your Web browser and type inside "http://localhost/CodeIgniter/index.php/Hello" OR "http://localhost/CodeIgniter/index.php/Hello/index"

    Explanation: Here Hello is Controller name and index is method name. By default index method automatically calls so if u want to call then type inside url otherwise leave method name.

    Output

    Creating Hello Controller with 2 methods index and about

    <?php 
       class Hello extends CI_Controller
       {  
          public function index() 
    	  { 
             echo "Hello World"; 
          }
    	  public function about() 
    	  { 
             echo "About us"; 
          }
       } 
    ?>
    

    Calling Hello Controller's index method

    http://localhost/CodeIgniter/index.php/Hello/index
    
    Output Hello World

    Calling Hello Controller's about method

    http://localhost/CodeIgniter/index.php/Hello/about
    
    Output About us