繁体   English   中英

如何在codeIgniter中定义全局变量(值)

[英]How to define a global variable(value) in codeIgniter

我根本不是在说如何在CodeIgniter中定义全局变量/常量。 让我解释一下:我制作了一个主题引擎,可以从当前登录的用户控制面板中选择它。 这个引擎不是很复杂,而是一个简单的文件夹。 无论如何,我在整个应用程序中所做的就是编写一行代码来获取用户选择的当前主题。 我使用一行代码来获取名称,然后将其存储在变量中:

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

然后,我使用$ theme_name这样的用户来获取正确的视图:

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

在所有加载视图的控制器中,我都应重复此过程。 我需要的是调用获取theme_name并存储在变量中的函数,然后在整个应用程序中使用变量/会话/函数。 我目前的方法是助手功能,与会话/变量相比,它的便利性要差一些。

在代码点火器中,可以在以下位置定义全局常量

config->constants.php

即使您无需加载,CI也会自动将其自动加载。

我从手册中得到了这个,这是我的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/libraries/config.html

以及如何访问控制器:

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

创建一个核心控制器,因为您的过程需要逻辑操作,所以您需要一种方法。

应用/型芯/ 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

应用/控制器/ view.php

class view extends MY_Controller
{
   public function index()
   {
     $this->load->view($this->get_theme().'result', $data);
   }
}
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM