CodeIgniter Controllers
0 2418
In Codeigniter, a controller works as an intermediary unit among the model, view, and any other processes needed to process the HTTP (Hypertext transfer protocol) request.
Related Topics:
Helpers in Codeigniter
Codeigniter Interview Questions
Syntax:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_name extends CI_Controller{
public function index()
{
}
}
?>
Explanation:
- The very first line is used to make the controller secure means one cannot access directly the controller file by entering the filename in the URL.
- Controller_name: It represents the name of the controller which we want to create. We have some rules to define the name of a controller.
- CI_Controller is a predefined Codeigniter class. Every controller extends this class to inherit the predefined public functions and variables of CI_Controller.
- Index(): It is the default function of the controller and it's mandatory.
1 The first character of the name should be in uppercase.
2 The name of the file and the name of the controller should be the same.
Creating a controller:
Controllers are stored inside the controller folder of the application directory. By default, the controller folder has two files.
- Index.html: This file contains the view.
- Welcome.php: This file contains the default controller of Codeigniter.
To create a new controller follow below steps:
Step 1 Create a new file Demo.php and save the given Demo class code in it.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Demo extends CI_Controller {
public function index()
{
echo "This the default function of Demo";
}
public function example()
{
echo "This the example function of Demo";
}
}
?>
Calling a controller:
Syntax:
http://localhost/index.php/controller_name/function_name
- controller_name: It is the name of the controller which we want to call. If we don’t give this parameter into the URL then by default Welcome controller is called.
- function_name: It is the name of the method which we want to execute inside the controller. If we do not give this parameter into the URL then the index() method is executed by the controller.
Related Topics:
Codeigniter Apllication Architecture
Codeigniter MVC Framework
To call the Demo controller created above we use the following URLs
http://localhost/ci/index.php/Demo
or
http://localhost/ci/index.php/Demo/index
Output:
Both above URLs executed the same method that is the index().
To execute the example() method use the following URL.
http://localhost/ci/index.php/Demo/example
Output:
Share:
Comments
Waiting for your comments