Posted by & filed under PHP/CodeIgniter.

If you have a block of code that should be invoked with each of your CodeIgniter controllers, you may not have found an obvious way to do this, other than using one controller for your entire project. Read on to learn how you can!

If you have a block of code that should be invoked with each of your CodeIgniter controllers, you may not have found an obvious way to do this, other than using one controller for your entire project. Perhaps the CodeIgniter documentation could be more clear in this regard, but this can be done by creating a core controller via these instructions.

Simply put, dump all of your code that should be shared between controllers into application/core/MY_Controller.php (the prefix of this should be set to whatever your “subclass_prefix” is set as, and if you aren’t using a core system class already you’ll have to create the “core” folder). Once you’ve done so, make sure that each of your controllers extends MY_Controller rather than the default CI_Controller, and you’re set!