Message Bridge let you trigger messages from anywhere in a procedural or in an object-oriented way. A registered callback can dispatch or forward all triggered messages. Main idea is to support a decoupled event driven and aspect oriented application, thus object awareness to any logger or any event dispatcher is not needed anymore.
Install the latest version with
$ composer require mamuz/message-bridge
// Register dispatch callback globally
set_message_dispatcher(function ($msg, $argv, $emitter) {
if ($msg == 'user.registered') {
mail('[email protected]', 'A new user entered', 'UserId ' . $argv['userId']);
}
});
// Trigger any message anywhere
trigger_message('user.registered', array('userId' => 1234));
$bridge = \MsgBridge\MessageBridge::getInstance();
$bridge->bindDispatcher(function ($msg, $argv, $emitter) use ($eventManager) {
$eventManager->trigger($msg, $argv, $emitter);
});
// ...
$bridge->trigger('user.registered', array('userId' => 1234));
To prevent side-effects the dispatcher can be registered with write protection.
$locked = true;
set_message_dispatcher($closure, $locked);
// This will throw a RuntimeException now
set_message_dispatcher($anotherClosure);
In Unit Tests you should not register a dispatcher with write protection, otherwise test isolation is not given. Instead of that implement following snippet to the tearDown method.
public function tearDown()
{
\MsgBridge\MessageBridge::getInstance()->unsetDispatcher();
}
As an alternative you can add the provided TestListener to your phpunit.xml. This Listener will do the job for you automaticly.
<phpunit>
<listeners>
<listener class="\MsgBridge\TestListener"></listener>
</listeners>
</phpunit>