CodeIgniter Methods

Next Page Previous Page

 In URLs, the second segment represents the method, the method is a procedure that is written to accomplish a task. Methods are usually unwritten inside the Application Controllers. With the help of methods, we can exchange data between the frontend and backend and perform logical operations.

Example: my_example1.com/index.php/codeIgniter_tutorial/index/

<?php
class Blog extends CI_Controller {

        public function index()
        {
                echo 'Hello Jack!';
        }

        public function comments()
        {
                echo 'How are you doing today!';
        }
}

Passing the URI segment to our methods :

With the help of the Uri segment, we can pass as many segments as we need to, all we will need is just pass some parameters to our method, Uri segment is the most used method in Codeigniter,.

Example:

Let’s consider we have a URI like this: 

my_example1.com/index.php/codeigniter_tutorial/methods/123456

Here We are  passing URI segments 3 and 4 (“methods” and “1234”)in our method

<?php
class Products extends CI_Controller {

        public function shoes($sandals, $id)
        {
                echo $methods;
                echo $id;
        }
}

Remapping Method Calls : 

The Remapping method is one of the most useful methods of Codeigniter allows us  to override this behavior in the second segments by using the _remap() method

Syntax:

public function _remap()
{
        // Enter some code for your method here...
}

Example:

public function _remap($method)
{
        if ($method === 'my_first_method') 
        {
                $this->$method();
        }
        else
        {
                $this->default_method();
        }
}

Private Methods:

We always have some methods which we want to hide from public eyes by declaring a method that can be private and protected we stop letting it served in the segment 

of our URL 

Syntax:

private function _utility()
{
        // Enter code of your private method here. 
}

If we try to access this with my_example1.com/index.php/code/_utility/

We won’t be able to reach this method because it is set to be a private method.

Class Constructor :

The constructor is a function with an identical name as the class name of our Controller. The constructor is applied to set default values and do default operations

Constructor can be easily added by using parent::__construct(); in our code

Syntax:

<?php
class Blog extends CI_Controller {

       	public function __construct()
       	{
                parent::__construct();
                // Enter your constructor code here...
}
}
?>
Next Page Previous Page

Treding Tutorial

Popular Tutorials

to Learn now