CodeIgniter Methods

 In the earlier Hello World example, our method name is index(). By default Controller always calls index method. If you want a different method, then write it in the Controller's file and specify its name while calling the function.

Codeigniter Methods 1

Look at the URL, there is no method name is mentioned. Hence, by default index method is loaded.


Method other than index()

Here, we have mentioned a method called newFunction(). Now we have to call this new method to run our program.

Create a controller page Hello.php in application/controllers.

  1. <?php  
  2. defined('BASEPATH') OR exit('No direct script access allowed');  
  3.   
  4. class Hello extends CI_Controller {  
  5.   
  6.     public function newfunction()  
  7.     {  
  8.         $this->load->view('hello_world');  
  9.     }  
  10. }  
  11. ?>  

Look at the above snapshot, we have created a function newFunction.

Create a view page hello_world.php in application/views.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>Hello World Example</title>  
  5. </head>  
  6. <body>  
  7.     <p>Hello World!!</p>  
  8. </body>  
  9. </html>  

To run this program on our browser, follow path

http://localhost/CodeIgniter/index.php/Hello/newFunction

Codeigniter Methods 4

Look at the above snapshot, we created the Controller's function as newFunction and specified it in the URL after Controller's name.

Here, /index.php/Hello is Controller's name.

And /newFunction is the Function name.


Remapping Method Calls

Second segment of URI determines which method is being called. If you want to override it you can use _remap() method.

If you have mentioned _remap() method in your controllers, it will always get called even if URI is different. It overrides the URI.

  1. public function _remap($methodName)  
  2. {  
  3.             if ($methodName === 'a_method')  
  4.             {  
  5.             $this->method();  
  6.             }  
  7.             else  
  8.             {  
  9.             $this->defaultMethod();  
  10.             }  
  11. }  

Comments

Popular posts from this blog

Codeigniter Pro Level Tips and Tricks

Login with Facebook in CodeIgniter

PHP - File Uploading