Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter: Hooks (pre_controller) loading helpers

I am trying to load the cookie helper in my pre_controller hook for a 'remember me' function on our site. I thought that creating an instance of the CI object with $ci =& get_instance(); would allow me to access to loading helpers but this is not the case.

Thoughts?

 $ci =& get_instance();
 $ci->load->helper('cookie');
 // does not load
like image 733
Thomas Avatar asked Feb 04 '10 00:02

Thomas


People also ask

What is the difference between library and helper in CodeIgniter?

The main difference between Helper and Library in CodeIgniter is that the Helper is a file with a set of functions in a particular category and is not written in Object Oriented format, while the Library is a class with a set of functions that allows creating an instance of that class and is written Object Oriented ...

What are the different types of hook point in CodeIgniter?

Hook Points No routing or other processes have happened. Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done. Called immediately after your controller is instantiated, but prior to any method calls happening.

What are the helpers in CodeIgniter?

There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.


2 Answers

The problem with the post_controller_constructor is it runs after the constructor (funnily enough) and if you use Controller constructors for lots of things this can be a problem.

If it's not a problem for you (your helper wont affect anything run or loaded in your constructors) fair enough, if it IS a problem you have two solutions.

  1. Instead of the hook put your code in MY_Controller
  2. Create MY_Controller and add in a custom hook point.

    class MY_Controller extends Controller
    {
    
        function MY_Controller()
        {
            parent::Controller();
            $GLOBALS['EXT']->_call_hook('pre_controller_constructor');
        } 
    }
    

Note that if you're using CodeIgniter 3.0 or later, the function _call_hook was renamed to call_hook.

like image 146
Phil Sturgeon Avatar answered Sep 28 '22 15:09

Phil Sturgeon


The pre_controller hook executes before the super object has been fully constructed, so get_instance() can't work - the static object it returns a reference to hasn't yet been initialized.

Consider using the post_controller_constructor hook instead; your controller's constructor will have executed, and the CI super object will be available for use.

like image 22
meagar Avatar answered Sep 28 '22 17:09

meagar