I have this bit of code
class Logger{
public static $messages = array();
public static function log($msg){
if(!empty($msg))
self::$messages[] = $msg;
}
}
class Model{
function foo(){
if(rand(1,5)>3) // This will only occasionally be true
Logger::log('bar2');
return 'bar1';
}
}
class Controller{
public function foo(){
$m = new Model();
Logger::log($m->foo());
}
}
$c = new Controller();
$c->foo();
print_r(Logger::$messages);
The result is
Array
(
[0] => bar2
[1] => bar1
)
I need it to be first bar1 then bar2, but it's not as simple as it seems. As I may not always have bar2 present, as well as I may have other messages that have been logged before and after this particular part that I'm showing, so sorting is not really an option. Other things I can not do are switch the order of functions being called in the controller, or in the model, because the controller uses the data returned by the model and logs it. Also I can't move the logging of bar2
in the controller because there are multiple controllers ( and possibly more future controllers ) that are going to be calling this model. What I can do is manipulate the logger class code, but I can't come up with a clean way to switch the position of these two messages.
Since you want synchronous logging for the controllers and deferred logging for the models, a "not that dirty" option would be to have 2 separate message queues in your logger.
Then you can either keep them apart as two different channels, or define one as main and the other as temporary, flushing the latter after the controller logged its messages.