Global class/functions - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: Global class/functions (/showthread.php?tid=58286) |
Global class/functions - El Forum - 05-30-2013 [eluser]epseix[/eluser] I'm being such a plank (posted this in wrong section). So, I'm finally getting the hang of the relationships between models, views and controllers - however... I have a question! If I wanted to call a global class/function of some kind, to connect with mySql and define default variables needed for every page (meta tags, title etc.) WHERE exactly would I place it, and HOW would I include it in the basic structure of MVC. Surely, having to repeat same class/function in every controller is unnecessary? Many thanks! Global class/functions - El Forum - 05-30-2013 [eluser]Pert[/eluser] Really depends what exactly are you trying to do. You can use <b>__construct()</b> magic method to run some code every time any controller methods are called: Code: class my_controller extends CI_Controller You can also set up a model for all your metadata, autoload it with <b>config/autoload.php</b> and you can access it using <b>$this->metadata</b>. Again, you can use <b>__construct</b> method to get any data from database, so you don't have to manually initiate fetch routine. Global class/functions - El Forum - 05-30-2013 [eluser]TheFuzzy0ne[/eluser] I would suggest that you put it into the constructor of a controller you want to extend (such as MY_Controller), or put it into a helper somewhere, to save you repeating your code. That means that if you ever need to change that code, you only need to change it in a single place. Global class/functions - El Forum - 05-30-2013 [eluser]CroNiX[/eluser] An alternative is just to create a library or helper and autoload it so it would be available to all controllers, libraries, helpers, views, etc. Global class/functions - El Forum - 05-31-2013 [eluser]epseix[/eluser] [quote author="CroNiX" date="1369955725"]An alternative is just to create a library or helper and autoload it so it would be available to all controllers, libraries, helpers, views, etc.[/quote] This does sound like the easiest method, and I can load the same helper in every controller by default... I've looked at the user guide regarding helpers and it's slightly overwhelming. I'm wondering if there's a good tutorial or forum topic explaining the exact method of creating a helper like this - step-by-step etc. (sorry, I'm a noob) |