CodeIgniter - best place to declare global variable

前端 未结 6 1927
逝去的感伤
逝去的感伤 2020-11-28 10:27

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

相关标签:
6条回答
  • 2020-11-28 11:05

    There is a file in /application/config called constants.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.php is loaded, it loads the /core/CodeIgniter.php file, which then in turn loads the common functions file /core/Common.php and then /application/constants.php so in the chain of things it's the forth file to be loaded.

    0 讨论(0)
  • 2020-11-28 11:10

    inside file 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';
    
    0 讨论(0)
  • 2020-11-28 11:19

    Similar to Spartak answer above but perhaps simpler.

    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.

    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

    Logging from modelName: testLogging

    Logging from customLibrary: testLogging

    0 讨论(0)
  • 2020-11-28 11:20

    The best place to declare global variable in codeigniter is the constants.php file in the directory /application/config

    You can define your global variable as follows

    /**
     * Custom definitions
     */
    define('first_custom_variable', 'thisisit');
    $yourglobalvariable = 'thisisimyglobalvariable';
    
    0 讨论(0)
  • 2020-11-28 11:22

    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_helper.php (in the helpers directory)

    <?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['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.

    0 讨论(0)
  • 2020-11-28 11:29

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

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

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

    $autoload['helper'] = array('contstants');
    
    0 讨论(0)
提交回复
热议问题