Anders Svensson Anders Svensson - 3 months ago 9
PHP Question

Run a function each time a page loads in CodeIgniter

I have previously only made web applications in Asp.Net MVC, and there you can use OnResultExecuted in an "ActionFilter" set on the BaseController to run a method each time an action method is executed (i.e. basically each time anyone visits any page in the application).

How would I do the same thing in CodeIgniter/PHP?

EDIT:

I tried using post_controller_constructor instead, according to one of the suggestions, but that doesn't help:

$hook['post_controller_constructor'] = array(
'class' => 'PreController',
'function' => 'getIp',
'filename' => 'preController.php',
'filepath' => 'hooks'
);


I still get Undefined property: PreController::$input (I just haven't renamed the class called, that shouldn't matter if it is still called PreController for the moment).

But the fact remains I do not have access to the input property... Obviously I don't have access to the Input Class, so how do I do that? I belive if I had done the same thing in a Controller it would have been ok, but from a hook? How do I do this?

Answer

You can use CodeIgniter hooks for that: http://www.codeigniter.com/user_guide/general/hooks.html

There are several "events" you can hook into, check the bottom of the documentation page.


In response to the comment:

Re-read your comment and edit... it seems that you're assuming that your hook class is the current controller -- it isn't. The current controller is whatever matches the URI/route mapping (for example, site.com/users/view/1 would be using the Users controller, and not your hook handler PreController class). The hook handler can be a simple PHP class not inheriting from CI_Controller.

The first thing you need to do in the hook handler is to get hold of the actual controller, that will contain the Input reference and others.

class HookHandler {
    function post_controller_constructor() {
        $ci =& get_instance();
        // ... now you can use $ci->input and other controller members
    }
}
Comments