Welcome Guest, Not a member yet? Register   Sign In
Global class/functions
#1

[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!
#2

[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
{
   function __construct()
   {
      parent::__construct();
      // repeating code starts from here
      ...
   }
   function method()
   {
      // what ever you did in __construct has already been run
      ...
   }
}

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.
#3

[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.
#4

[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.
#5

[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) Smile




Theme © iAndrew 2016 - Forum software by © MyBB