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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17013397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:05:39  来源:igfitidea点击:

CodeIgniter - best place to declare global variable

phpcodeigniterglobal-variablesglobal

提问by J. Bruni

I just want to use a $variableat several places: not only views and controllers, but also in the routes.phpand other configuration files.

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

I don't want things like: use the Config class to load configuration files; use CI's get_instance, et cetera.

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

I just want to declare a given $variable(it could be a constant, but I need it as a variable), and use it absolutely everywhere.

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

In fact... I'd like to know which PHP file in the CI bootstrap is one of the first to be parsed, so I could introduce my global variable there... but not a core/system or inapproriated file, but the "best" suited placement for this simple requirement.

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

回答by Dale

There is a file in /application/configcalled constants.php

有一个文件/application/configconstants.php

I normally put all mine in there with a comment to easily see where they are:

我通常把我所有的都放在那里,并附上评论,以便轻松查看它们的位置:

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

After your index.phpis loaded, it loads the /core/CodeIgniter.phpfile, which then in turn loads the common functions file /core/Common.phpand then /application/constants.phpso in the chain of things it's the forth file to be loaded.

你之后index.php被加载,它加载的/core/CodeIgniter.php文件,然后依次加载常用功能的文件/core/Common.php,然后/application/constants.php在事物的链条,它是要加载第四文件。

回答by Spartak

I use a "Globals" class in a helper file with static methods to manage all the global variables for my app. Here is what I have:

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

globals_helper.php (in the helpers directory)

globals_helper.php(在 helpers 目录中)

<?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;
    }
}

Then autoload this in the autoload.php file

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

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

Lastly, for usage from anywhere within the code you can do this to set the variables:

最后,对于代码中任何地方的使用,您可以这样做来设置变量:

Globals::setAuthenticatedMemeberId('somememberid');

And this to read it:

这是阅读它:

Globals::authenticatedMemeberId()

Note: Reason why I left the initialize calls in the Globals class is to have future expandability with initializers for the class if needed. You could also make the properties public if you don't need any kind of control over what gets set and read via the setters/getters.

注意:我将 initialize 调用留在 Globals 类中的原因是,如果需要,将来可以使用该类的初始值设定项进行扩展。如果您不需要对通过 setter/getter 设置和读取的内容进行任何类型的控制,您也可以将属性设为公开。

回答by Spartak

inside file application/conf/contants.php :

在文件 application/conf/contants.php 中:

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

and put in some header file or inside of any function:

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

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

回答by lucentx

You could also create a constants_helper.php file then put your variables in there. Example:

您还可以创建一个 constants_helper.php 文件,然后将您的变量放入其中。例子:

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

Then on your application/config/autoload.php, autoload your contstants helper

然后在您的 application/config/autoload.php 上,自动加载您的常量助手

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

回答by Mad Angle

The best place to declare global variablein codeigniteris the constants.phpfile in the directory /application/config

申报最好的地方global variablecodeigniterconstants.php在目录中的文件/application/config

You can define your global variable as follows

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

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

回答by Zac Imboden

Similar to Spartak answer above but perhaps simpler.

类似于上面的 Spartak 答案,但可能更简单。

A class in a helper file with a static property and two instance methods that read and write to that static property. No matter how many instances you create, they all write to the single static property.

帮助程序文件中的一个类,具有一个静态属性和两个读取和写入该静态属性的实例方法。无论您创建多少个实例,它们都会写入单个静态属性。

In one of your custom helper files create a class. Also create a function that returns an instance of that class. The class has a static variable defined and two instance methods, one to read data, one to write data. I did this because I wanted to be able to collect log data from controllers, models, libraries, library models and collect all logging data to send down to browser at one time. I did not want to write to a log file nor save stuff in session. I just wanted to collect an array of what happened on the server during my ajax call and return that array to the browser for processing.

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

In helper file:

在帮助文件中:

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();

    }
}

In any controller, where you might want to output all log entries made by the controller or by a library method called by the controller or by a model function called by the controller:

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

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());
}

Prints out:

打印出来:

Logging from controllerName: testLogging

从控制器名称登录:testLogging

Logging from modelName: testLogging

从模型名称记录:testLogging

Logging from customLibrary: testLogging

从 customLibrary 记录日志:testLogging