Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is hook in Codeigniter and how to use this

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 5.69k
    Comment on it

    Hello Friends,

    Some time we need some functionality before execution of our controller function or after execution of controller. For example you need to check a user is login or not before execution of any controller. Codeigniter hook is a very good functionality to solve this kind of problem, it save time to writing code multiple time. Lets have a below example for pre hook as below::

    1) Open "Config.php" and change the statement

    $config['enable_hooks'] = FALSE;
    // Change this statement to true
    $config['enable_hooks'] = TRUE;

    2) Now I have created a Controller "Codeigniter/application/controllers/Hello.php" with below code::

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Hello extends CI_Controller {
    	function index(){
    		echo "My name is Vivek";
    	}
    
    }
    
    ?>

     **** When I run this code on browser it will display "My name is Vivek"

    3) Now I have created a file "application/hooks/Hookcall.php" and save this on below path ::

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Hookcall extends CI_Controller {
    	public function temp(){
    		echo "Good Morning, Everyone";
    	}
    }
    ?>

    4) Now I open do open "Codeigniter/application/config/hooks.php" and paste code shown below::

    $hook['pre_controller'] = array(
                                    'class'    => 'Hookcall',
                                    'function' => 'temp',
                                    'filename' => 'Hookcall.php',
                                    'filepath' => 'hooks'
                                    );
    

    5) Now see the magic when you run "http://localhost/codelgniter/hello" Now it will display

    *** "Good Morning, Everyone My name is Vivek"

     

     

 1 Comment(s)

  • Hi,
    i follow the code written by you. When i load the controller it show the message "Good Morning, EveryoneUnable to locate the specified class: Cache.php"
    Can you please tell me why it is showing the message like this?
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: