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
constants.php
... it seems a nice place. I've added my$GLOBALS['variable'] = 'my stuff';
code there, and it is available atroutes.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