How to create Hooks in Codeigniter
Today, we will explain to you how to create custom 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.
Overview
Step 1: Enabling Hooks in Codeigniter
Step 2: Define Hooks in Codeigniter
Step 3: Create Controller
Step 1: Enabling Hooks in Codeigniter
In this step, we have to change the hook configuration. now we will open the “application/config/config.php” file and enable the hook.
1 | $config['enable_hooks'] = TRUE; |
Step 2: Define Hooks in Codeigniter
Now, the hooks are defined in the “application/config/hooks.php” file. so you can see below code.
1 2 3 4 5 6 7 | $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.
Step 3: Create Controller
Finally, we will create a Myfirsthook.php file in the “application/hooks/” directory and paste the below code in this controller.
1 2 3 4 5 6 7 8 | <?php class Myfirsthook extends CI_Controller { public function index() { echo "Hi, Welcome To In My First Hook"; } } ?> |
Now, We will define hook using the below code (on above step2).
1 2 3 4 5 6 7 | $hook['pre_controller'] = array( 'class' => 'Myfirsthook', 'function' => 'index', 'filename' => 'Myfirsthook.php', 'filepath' => 'hooks', 'params' => array() ); |