CodeIgniter Forums
Is there a way to run a controller method before all other methods? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Is there a way to run a controller method before all other methods? (/showthread.php?tid=68319)



Is there a way to run a controller method before all other methods? - desbest - 06-23-2017

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.


RE: Is there a way to run a controller method before all other methods? - PaulD - 06-23-2017

Hi,

You could try hooks:
https://www.codeigniter.com/user_guide/general/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.


RE: Is there a way to run a controller method before all other methods? - Wouter60 - 06-25-2017

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.


RE: Is there a way to run a controller method before all other methods? - Kaosweaver - 06-26-2017

If you need something sitewide to run before any other controller code does, extend the controllers (https://www.codeigniter.com/user_guide/general/core_classes.html) and put that code in the MY_controller.php __construct() method to make sure it is run sitewide every time.