Global variables in CodeIgniter view Global variables in CodeIgniter view codeigniter codeigniter

Global variables in CodeIgniter view


Personally, I would create a base controller for each site that you extend, and just use $this->load->vars($data); to load the information you need globally set.

In the constructor of your specific base Controller just load the data into the views globally like this.

$data->some_var = "some value";$this->load->vars($data);

And then in all your views loaded by this controller (or base controller) you can utilize the variable $some_var directly in the view.


Your best bet is probably option 3, to put it in the constructor of your base contoller, probably MY_controller or whatever you are extending Controller (now CI_Controller with the CI2.0 official release)

However if all you're doing is getting an extension, there might not be a reason to have a database table, since you could just keep it in a config file

I'd do something like this... in MY_Controller.php (This is CI 2.0 syntax)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class MY_Controller extends CI_Controller {      function __construct()      {           parent::__construct();           $subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);             $subdomain_name = $subdomain_arr[0];             $this->load->config('sub_prefix');           $pre_arr = $this->config->item('prefixes');           /* Check to make sure the subdomain name is in the config array */           $this->prefix = isset($pre_arr[$subdomain_name]) ? $pre_arr[$subdomain_name] : '';      }

Then in the config file (sub_prefix.php)

<?php if (! defined('BASEPATH')) exit('No direct script access');    $config['prefixes'] = array('subdomain1' => 'sub1',                                 'stackoverflow' => 'sf');

That way you don't have to run an extra query everytime the page loads for something that is relatively static...if you got to the point where there would be a lot more information you would need other than a prefix, then it would make sense to do it with the database

You can now just use $this->prefix in any of the views, controllers, or models you will be using... the best way to do it for something that is heavily use all over your application.