CodeIgniter - 声明全局变量的最佳位置

时间:2013-06-09 19:36:22

标签: php codeigniter global-variables global

我只想在几个地方使用$variable:不仅包括视图和控制器,还包括routes.php和其他配置文件。

我不想要这样的事情:使用Config类加载配置文件;使用CI的get_instance等等。

我只想声明一个给定的$variable(它可能是一个常量,但我需要它作为变量),并且绝对在任何地方使用它。

实际上......我想知道CI引导程序中的哪个PHP文件是最先被解析的文件之一,所以我可以在那里引入我的全局变量......但不是核心/系统或不相关的文件,但这个简单要求的“最佳”适合放置。

7 个答案:

答案 0 :(得分:34)

/application/config中有一个名为constants.php

的文件

我通常会把我的所有人都放在那里,以便轻松查看它们的位置:

/**
 * Custom defines
 */
define('blah', 'hello mum!');
$myglobalvar = 'hey there';

加载index.php后,它会加载/core/CodeIgniter.php文件,然后加载公共函数文件/core/Common.php,然后加载/application/constants.php,以便在事物链中加载这是要加载的第四个文件。

答案 1 :(得分:3)

我在一个带有静态方法的帮助文件中使用“Globals”类来管理我的应用程序的所有全局变量。这就是我所拥有的:

globals_helper.php(在帮助程序目录中)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Application specific global variables
class Globals
{
    private static $authenticatedMemberId = null;
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$authenticatedMemberId = null;
        self::$initialized = true;
    }

    public static function setAuthenticatedMemeberId($memberId)
    {
        self::initialize();
        self::$authenticatedMemberId = $memberId;
    }


    public static function authenticatedMemeberId()
    {
        self::initialize();
        return self::$authenticatedMemberId;
    }
}

然后在autoload.php文件中自动加载

$autoload['helper'] = array('globals');

最后,要在代码中的任何位置使用,您可以执行此操作来设置变量:

Globals::setAuthenticatedMemeberId('somememberid');

这是为了阅读它:

Globals::authenticatedMemeberId()

注意:我在Globals类中保留初始化调用的原因是,如果需要,可以使用该类的初始化程序进行扩展。如果您不需要对通过setter / getters设置和读取的内容进行任何控制,您也可以公开属性。

答案 2 :(得分:2)

您还可以创建一个constants_helper.php文件,然后将变量放在那里。例如:

define('MY_CUSTOM_DIR', base_url().'custom_dir_folder/');

然后在您的应用程序/ config / autoload.php上,自动加载您的常规助手

$autoload['helper'] = array('contstants');

答案 3 :(得分:1)

内部文件application / conf / contants.php:

global $myVAR;
$myVAR= 'http://'.$_SERVER["HTTP_HOST"].'/';

并放入一些头文件或任何函数内部:

global $myVAR;
$myVAR= 'some value';

答案 4 :(得分:0)

global variable中声明codeigniter的最佳位置是目录constants.php

中的/application/config文件

您可以按如下方式定义全局变量

/**
 * Custom definitions
 */
define('first_custom_variable', 'thisisit');
$yourglobalvariable = 'thisisimyglobalvariable';

答案 5 :(得分:0)

类似于上面的Spartak答案,但也许更简单。

帮助器文件中的类,具有一个静态属性和两个可以对该静态属性进行读写的实例方法。无论您创建多少实例,它们都将写入单个静态属性。

在您的一个自定义帮助文件中创建一个类。还创建一个返回该类实例的函数。该类具有一个定义的静态变量和两个实例方法,一个用于读取数据,一个用于写入数据。我这样做是因为我希望能够从控制器,模型,库,库模型中收集日志数据,并收集所有日志数据以一次发送到浏览器。我不想写入日志文件,也不想在会话中保存内容。我只是想收集ajax调用期间服务器上发生的事情的一个数组,然后将该数组返回给浏览器进行处理。

在帮助文件中:

if (!class_exists('TTILogClass')){
    class TTILogClass{


        public static $logData = array();


        function TTILogClass(){


        }

        public function __call($method, $args){
            if (isset($this->$method)) {
                $func = $this->$method;
                return call_user_func_array($func, $args);
            }
        }

        //write to static $logData
        public function write($text=''){
            //check if $text is an array!
            if(is_array($text)){
                foreach($text as $item){
                    self::$logData[] = $item;
                }
            } else {
                self::$logData[] = $text;
            }
        }

        //read from static $logData
        public function read(){
            return self::$logData;
        }

    }// end class
} //end if

//an "entry" point for other code to get instance of the class above
if(! function_exists('TTILog')){
    function TTILog(){  
        return new TTILogClass();

    }
}

在任何控制器中,您可能希望输出由该控制器,由该控制器调用的库方法或由该控制器调用的模型函数创建的所有日志条目:

function testLogging(){
    $location = $this->file . __FUNCTION__;
    $message = 'Logging from ' . $location;

    //calling a helper function which returns 
    //instance of a class called "TTILogClass" in the helper file

    $TTILog = TTILog();

    //the instance method write() appends $message contents
    //to the TTILog class's static $logData array

    $TTILog->write($message);

    // Test model logging as well.The model function has the same two lines above,
    //to create an instance of the helper class TTILog
    //and write some data to its static $logData array


    $this->Tests_model->testLogging();

    //Same thing with a library method call
    $this->customLibrary->testLogging();

    //now output our log data array. Amazing! It all prints out!
    print_r($TTILog->read());
}

打印出:

从controllerName登录:testLogging

从modelName登录:testLogging

从customLibrary登录:testLogging

答案 6 :(得分:0)

CodeIgniter 4 - 声明全局变量的最佳位置

在 CodeIgniter 4 中,我们有一个像 app/config/Constant.php 这样的文件夹,所以你可以在 Constant.php 文件中定义一个全局变量。

define('initClient_id','Usqrl3ASew78hjhAc4NratBt'); 定义('initRedirect_uri','http://localhost/domainName/successlogin');

从任何控制器或库,您都可以通过名称访问

echo initClient_id;或 print_r(initClient_id);

echo initRedirect_uri;或 print_r(initRedirect_uri);

基本上,在部署到服务器之前,我已经将 dev 和 production 的所有 URL 作为变量放在 Constant.php 中,我只是注释了 dev 变量

codeignitor 4 文件的加载是这样的

加载 index.php 后,它会加载 /core/CodeIgniter.php 文件,然后依次加载常用函数文件 /core/Common.php 和 /application/constants.php一系列事物,它是要加载的第四个文件。