Showing posts with label codeigniter functions. Show all posts
Showing posts with label codeigniter functions. Show all posts

Friday, January 26, 2018

Controllers and its functions in Codeigniter

What is a Controller ?

A Controller is simply a class file that is named in a way that can be associated with a URI. Consider this URI: example.com/index.php/ blog / In the above example,CodeIgniter would attempt to find a controller named blog.php and load it. When a controller's name matches the first segment of a URI, it will be loaded.

As you all know about the URI segments. In codeigniter, the first segment is the name of the controller. The second segment is the name of that controller's method which is being called. And the third segment can b any value that is passed in any method as a parameter. e.g

www.example.com/Mycontroller/method/parameter

Creating a Controller:

You can create a controller simply by opening the controller folder, its path is as follow:

....htdocs/codeigniter/applications/controller

After opening the controller folder, create a new file by giving the name of your choice and save it with a .php extension. Keep the UCfirst approch in naming your controller i.e keep the first letter of your controller's name capital. It is a good practise. e.g Mycontroller.php

After creating your file write the following code in that file. Firstly, to make that file work as a controller, you need to extend the parrent class of controller that is CI_Controller. Here is an example of syntax of declaring and defining a controller class:


This is valid:

<?php class MyController extends CI_Controller {
//name of the class is same as you have given the name to the controller file
}
?>

This is not valid:

<?phpclass myController extends CI_Controller {
//name of the class cannot have first letter in lower case
//class cannot have any other name than the one with which the controller file is saved
}
?>

Creating a Controller's Methods/Functions:
Now, after creating class of controller and extending it from the parent controller class, you can define methods or functions here in the controller. Every controller class calls a by default function that is index(). Here is the syntax to declare and define a method or function in controller e.g
<?phpclass MyController extends CI_Controller {
public function index(){
//default function
echo"I am a by default function";
}
public function myFunction(){
//user defined function
echo"I am a user defined function";
}
}
?>