How to define a global variable(value) in codeIgni

2019-02-26 10:27发布

问题:

I simply do not mean how to define a global variable/constant in CodeIgniter. Let me explain: I have made a theme engine which is select-able from the current logged in user's control panel. This engine is not very complicated, but a simple folder. anyway, what I do across the application, is that I write one line of code to get the current theme selected by the user. I use a one line of code to get the name, and then store it in a variable:

$theme_name = $this->theme->get_theme_with_slash(false);

And then, I user $theme_name like this to get the proper view:

$this->load->view($theme_name.'result', $data);

And in all of my controllers that loads view I should repeat this process. What I need, is to call the function which gets the theme_name and store in the variable and then use the variable/session/function across the application. My approach currently is the helper's function which is a little less convenient compared to session/variable.

回答1:

Create A core controller, since your process requires logical operations then you need a method for that.

application/core/MY_Controller.php

class MY_Controller Extends CI_Controller
{

   protected $default_theme = 'theme';

   public function __construct()
   {
      parent::__construct();
   }

   public function get_theme()
   {
         //your code for selecting the current theme selected from
         //the database
         $theme_from_db = '';

         return $theme_from_db == NULL ? $this->default_theme : $theme_from_db;
   }
}

Your Controller must extend MY_Controller

application/controller/view.php

class view extends MY_Controller
{
   public function index()
   {
     $this->load->view($this->get_theme().'result', $data);
   }
}


回答2:

in code igniter global constants can be defined in

config->constants.php

even you no need to load it,it automatically autoloaded by CI automatically.



回答3:

I got this from the manual and this what I have at the top of my config/config.php file: (i have a custom config set to paypal testing)

// HOW TO USE - For example if there's $config['foo'] = 'bar';
// in the config 
// using $this- >config->item('foo') will be 'bar'.

// example for my paypal testing: 
$config['paypaltest']=0;  

http://ellislab.com/codeigniter%20/user-guide/libraries/config.html

and how to access in a controller:

$paypaltest = $this->config->item('paypaltest');


回答4:

In Codeigniter all constant is defined inside application/config/constant.php.
like: define("CONSTANTNAME","value");

Constant degined here is accessible throughout all pages, ie; controllers, models and views