Chapter 9. Zym_Message

Chapter 9. Zym_Message

Table of Contents

9.1. Registering a message

Zym_Message provides an infrastructure to relay messages between objects that don't necessarily know each other. This provides a loose coupling between components and makes your app more flexible.

9.1. Registering a message

Registering to a message is done at Zym_Message:

Example 9.1. Registering a message

<?php
$message = Zym_Message_Dispatcher::get();
$message->attach($theReceivingObject, $testEvent, $customMethod);

In this snippet, an object is attached to the testEvent message. All posts that are sent to the ‘testEvent’ message will then be passed to the $receivingObject. By default the notifications will be posted to the notify() method. An optional third parameter in the attach() method allows you to use a custom method.

In this case, all ‘testEvent’ notifications will be posted to the customMethod() method in $theReceivingObject. There is a special attach method called attachCatchAll(). An object that is registered to the catch-all will receive all notifications. If you want to unregister an object from the message dispatcher you can call the detach() method. This method takes one mandatory and one optional argument. The first argument is the object you want to detach. The second, optional, argument is the message that you want to detach the object from. If the second argument is left blank, the message dispatcher will remove the object from all notifications. Don’t forget to detach an object when it’s destroyed! See the next section for an example of how to make sure this gets done.

Example 9.2. Attaching, Detaching and Receiving Notifications

<?php
class MyClass
{
    protected $_message;
 
    public function __construct()
    {
        $this->_message = Zym_Message_Dispatcher::get();
        $this->_message->attach($this, 'testEvent');
    }
 
    public function __destruct()
    {
        $this->_message->detach($this);
    }
 
    public function notify(Zym_Message $message)
    {
        if ('testEvent' == $message->getName()) {
            // Assume Zend_Log instance
            $log = Zend_Registry::get('log');
            $log->log('testEvent was triggered and received by MyClass!');
        }
    }
}

In the example above the MyClass instance is automatically registered to the ‘testEvent’ message at instantiation. If and when the ‘testEvent’ message is sent, the notify() method will receive it so it can be processed. Note the __destruct() method which explicitly detaches the object from the message dispatcher.