CodeIgniter - best place to declare global variable
Asked Answered
R

8

25

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.

Renettarenew answered 9/6, 2013 at 19:36 Comment(0)
A
46

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.

Ascender answered 9/6, 2013 at 19:41 Comment(9)
Although the PHP file name becomes misleading if we declare a global variable at constants.php... it seems a nice place. I've added my $GLOBALS['variable'] = 'my stuff'; code there, and it is available at routes.php, as I wanted, so surely it is available at controllers, views, et cetera. +1 (I will wait for other answers before accepting as solution; maybe someone has a better suggestion.)Renettarenew
CodeIgniter is really flexible, you could for instance, totally tweak the index.php file and ram it full of variables if you wish :) I just like to keep all mine in the constants file as it seems (to me at least) the best place for them.Ascender
Or maybe a better suggestion would be to include your custom variables in another file, at the top of the index.php file. Might be more to your liking.Ascender
Indeed. :) And not that I am a global variable fan... It will be the first time in almost 10 years w/ PHP that I will use $GLOBALS! It is just the "perfect" fit to solve my actual issue quickly and effectively, and with simplicity.Renettarenew
Your new suggestions are fine. By now, I will stay with constants.php because it is the most simple solution, and it is in a standard file, inside the application folder... seems less "hacky" than modifying CI's index.php, in my opinion. Thank you!Renettarenew
No problem :) glad to have helped outAscender
I put a variable on config.php and try to print it with echo inside a view and I can't why? @AscenderEpitomize
@Ascender This works for me thanks. Can you please help me, how can I access $myglobalvar in the controller, model and view?Martineau
This however is not available in view's unless explicitly passed to the view variables by the controller, hence in essence this answer does not exactly answer the question. Just because the constant is not really global as its not available in view.Bearer
N
7

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.

Nobby answered 24/5, 2015 at 17:42 Comment(2)
It's not working every time it will return a null value.Commutative
you should verify result getter before to ensure value is settedNiue
A
2

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');
Aerial answered 11/12, 2013 at 7:34 Comment(0)
E
2

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';
Epitomize answered 10/4, 2015 at 23:21 Comment(0)
T
1

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.

Theirs answered 18/6, 2021 at 20:16 Comment(0)
H
0

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';
Halima answered 10/9, 2014 at 11:36 Comment(0)
C
0

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

Crossfertilize answered 18/2, 2020 at 1:48 Comment(0)
K
0

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());
    }
}
Kempis answered 14/4, 2023 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.