J. Bruni
J. Bruni

Reputation: 20492

CodeIgniter - best place to declare global variable

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.

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

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.

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.

Upvotes: 25

Views: 116521

Answers (8)

Kosmas
Kosmas

Reputation: 385

Might be not the best place, but the constant that I need to define is after reading it from an external source. In order to tackle this, we did it using hooks.

https://www.codeigniter.com/userguide3/general/hooks.html

Enable hooks in the config.php

Edit/add hooks.php

$hook['post_controller_constructor'] = array(
    'class'    => 'PostContructorHook',
    'function' => 'initialize',
    'filename' => 'PostContructorHook.php',
    'filepath' => 'hooks',
);

add file in the hooks folder. PostContructorHook.php

class PostContructorHook {
    function initialize(){
        if (defined('MY_CONSTANT')){
            return;
        }
        $CI = & get_instance();
        $CI->load->model('vendorModel', 'vendorModel'); //load the caller to external source
        define('MY_CONSTANT',$CI->vendorModel->getConstant());
    }
}

Upvotes: 0

maneesh kumar gautam
maneesh kumar gautam

Reputation: 137

CodeIgniter 4 - best place to declare global variable

In CodeIgniter 4, we have a folder like app/config/Constant.php so you can define a global variable inside the Constant.php file.

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

from any controller or library, you can access by just name like

echo initClient_id; or print_r(initClient_id);

echo initRedirect_uri; or print_r(initRedirect_uri);

basically, I have put all the URL of dev and production in Constant.php as a variable before deploying into server I just comment the dev variables

the loading of codeignitor 4 file is in such manner

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 fourth file to be loaded.

Upvotes: 1

Zac Imboden
Zac Imboden

Reputation: 771

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

Upvotes: 0

Spartak
Spartak

Reputation: 149

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.

Upvotes: 7

user1817927
user1817927

Reputation:

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';

Upvotes: 2

Mad Angle
Mad Angle

Reputation: 2330

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';

Upvotes: 0

lucentx
lucentx

Reputation: 161

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

Upvotes: 2

Dale
Dale

Reputation: 10469

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.

Upvotes: 46

Related Questions