Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom hooks in codeIgniter?

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?

like image 241
Anup Avatar asked Mar 24 '15 11:03

Anup


1 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.

$EXT->_call_hook('pre_controller');

$CI = new $class();

$EXT->_call_hook('pre_controller_constructor');

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 https://ellislab.com/codeigniter/user-guide/general/hooks.html

like image 177
Philip Avatar answered Sep 24 '22 03:09

Philip