CodeIgniter Forums

Full Version: Is there a way to run a controller method before all other methods?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a way to run a controller method before all other methods?
So I can have 10 methods, and there is one method which runs before all 10 of them?
I looked at the Controllers section of the documentation and the instructions for how to do this are not there.
Hi,

You could try hooks:
https://www.codeigniter.com/user_guide/g...hooks.html
Sounds like you might want a post_controller_constructor hook point.

Alternatively you might do these in the class constructor: http://php.net/manual/en/language.oop5.decon.php

I suppose it depends what exactly you want to achieve.

Hope that helps,

Paul.
The __construct() method in a controller is always executed first, before any other method.  I use it to check if a user has access rights to the controller, or to initiate controller wide variables.
If you need something sitewide to run before any other controller code does, extend the controllers (https://www.codeigniter.com/user_guide/g...asses.html) and put that code in the MY_controller.php __construct() method to make sure it is run sitewide every time.