I my framework I have some functions that when done they can add some messages to a queue for reporting.
Example: I have a function that takes a path of a photo and
I have a global $msgQueue=array();
and whenever all the logic of the page is done, in my template I echo to the users all the reports (that the functions could add during the exectuion).
In that case 2 messages would be added to $msgQueue:
But this kind of behaviour I think it's not standard. If I want share with someone one of my function (in this case is checkImage($path)
) It can't work because the functions needs that global array to put their report msgs.
Is there a standard approach to solve this so I can share my functions with someone else and don't worry about this dependence?
My suggestion would be to use a class, something like:
class Report(){
public $msgQueue;
function addReport($string){
array_push($this->msgQueue, $string); //store new report
}
function showReports(){
//loop over the message queue
...
}
}
Benefits:
You could have different kind of reports using the same class, separating process from errors for example, $processes = new Report
and $errors = new Report
No need to declare vars as globals, the class preserves the value of its property $msgQueue
you would only need to $processes->addReport("Resizing image to XXX")
The benefits of OOP, having a logical structure, etc.
I don't really think there is a standard approach. What I do is this:
Give each library (Image, File, etc..) its own message array.
Use a Message library that has its own message array as well as an array of "sources" that can be built/added to via Message::addSource($class, $propertyName)
. (I add a message source right after I make an instance of a library, such as Image).
Doing it that way allows each library to be independent of others while still being able have both a per-instance and global message array.
Is there a standard approach to solve this?
Yes, its called OOP :) (see amosrivera's answer for that).
But if OOP is not an option (but you should seriously consider it nonetheless), then refactoring the functions to accept a messageQueue argument (and passing it by reference) might work.
// passing $messageQueue by reference by prepending &
function checkImage( $path, array &$messageQueue = null )
{
/* do image checking */
$result = /* the result of the image checking */;
// if $messageQueue argument is provided
if( $messageQueue !== null )
{
// add the message to the queue
$messageQueue[] = 'Image checking done';
}
return $result; // false or true perhaps.
}
Usage:
$messageQueue = array();
if( checkImage( $somePath, $messageQueue ) )
{
echo 'checking image succeeded';
}
else
{
echo 'checking image failed';
}
var_dump( $messageQueue );
// would output something like:
Array(1) (
'Image checking done'
)