我不是指如何在CodeIgniter中定义全局变量/常量。让我解释一下:我做了一个主题引擎,可以从当前登录用户的控制面板中选择。这个引擎不是很复杂,而是一个简单的文件夹。无论如何,我在整个应用程序中所做的就是写一行代码来获得用户选择的当前主题。我使用一行代码来获取名称,然后将其存储在一个变量中:
$theme_name = $this->theme->get_theme_with_slash(false);
然后,我像这样使用$theme_name来获得正确的视图:
$this->load->view($theme_name.'result', $data);
在我所有加载视图的控制器中,我应该重复这个过程。我需要的是调用获取theme_name并存储在变量中的函数,然后在整个应用程序中使用变量/session/函数。我目前的方法是助手的函数,与会话/变量相比,它稍微不那么方便。
我从手册中得到了这个,这就是我在config/config.php文件顶部的内容:(我有一个自定义的配置集,用于贝宝测试)
// 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/librarys/config.html
以及如何在控制器中访问:
$paypaltest = $this->config->item('paypaltest');
创建一个核心控制器,因为您的流程需要逻辑运算,所以您需要一个实现逻辑运算的方法。
应用程序/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;
}
}
您的控制器必须扩展MY_Controller
application/controller/view.php
class view extends MY_Controller
{
public function index()
{
$this->load->view($this->get_theme().'result', $data);
}
}
在代码中,点火器全局常量可以在中定义
config->constants.php
即使您不需要加载它,它也会自动由CI自动加载。
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