Today, we will explain to you how to use hooks in Codeigniter Framework. let’s know, what are hooks in Codeigniter. The hook allows you to execute a script without changing the core files. so we give you an example of how to implement hooks in Codeigniter.
There are two link files in CodeIgniter. One is the application/config/hooks.php folder and the other is the application/hooks folder.
In this step, we have to change the hook configuration. now we will open the “application/config/config.php” file and enable the hook.
$config['enable_hooks'] = TRUE;
Now, the hooks are defined in the “application/config/hooks.php” file. so you can see below code.
$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => array('beer', 'wine', 'snacks')
);
Class: The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank.
Function: The function (or method) name you wish to call.
Filename: The file name containing your class/function.
Filepath: The name of the directory containing your script. Note: Your script must be located in a directory INSIDE your application/ directory, so the file path is relative to that directory.
Finally, we will create a Myfirsthook.php file in the “application/hooks/” directory and paste the below code into this controller.
<?php
class Myfirsthook extends CI_Controller {
public function index() {
echo "Hi, Welcome To In My First Hook";
}
}
?>
Now, We will define the hook using the below code (in the above step2).
$hook['pre_controller'] = array(
'class' => 'Myfirsthook',
'function' => 'index',
'filename' => 'Myfirsthook.php',
'filepath' => 'hooks',
'params' => array()
);