Home » Php » php – How to create custom hooks in codeIgniter?

php – How to create custom hooks in codeIgniter?

Posted by: admin July 12, 2020 Leave a comment


I’m making a PHP application in codeIgniter, and want flexibility using hooks. However, there are a limited number of hooks in codeIgniter, so I want to create my own.

How can I do this?

How to&Answers:

You should open system/core/Codeigniter.php and look where the hooks are getting called and at what part in the page lifecycle.

On line 299 you have a hook getting called, then a $class is getting initialized, then another hook is getting called.


$CI = new $class();


So what’s happening is Codeigniter will grab the list of pre_controller hooks and execute them before $class is initialized. After $class has been initialized and the __constructor does it’s thing, the list of __pre_controller_constructor hooks will get executed.

So what is $CI = new $class() ?

The $class comes from the router, which has already been initialized at this point

So if the url is pointing to mysite.com/category/products then $class=='category' so what is really happening is this $CI = new Category(); // application/controllers/category.php

If a hook is called before the function function &get_instance(){} on line 232 then you won’t be able to access the super object as the function has not yet been created. At that point your dealing with PHP alone and won’t be able to access the framework.

The full documentation on hooks can be found here