I would like to have a library class that maintains state on the same request. My use case is that I want to pass “messages” to the class, and then call them anytime from the view. Messages can be added from any part of the application.
I initially did this using static methods that worked just fine. However, as part of lib, I also need to call __construct and __destruct() , which cannot be done in a static class.
Here is a very simple example of what I'm trying to do:
class Messages { private static $messages = array(); public function __construct() { // do something } public function __destruct() { // do something else } public static function add($message) { self::$messages[] = $message; } public static function get() { return self::$messages; } }
Then I can add messages anywhere in my code by doing
Messages::add('a new message');
I would like to avoid using statics, if at all possible (testability). I looked at the DI, but that does not seem appropriate unless I miss something.
Instead, I could create a class (non-static), but how can I ensure that all messages are written to the same object so that I can load them later?
What is the best way to handle this?
source share