Dispatching Messages

When certain actions occur you may want to dispatch messages for one of various reasons:

  • Provide extensibility allowing other developers to have additional PHP code executed upon the action via event listeners (eg. user created).
  • Allow it to be processed by a remote server for horizontal scaling.
  • Add it to a one-way queue to be processed by a remote server.

Messages can be dispatched by utilizing the Apex\Svc\Dispatcher and Apex\Svc\MessageRequest classes, fo example:


namespace App\MyProgram;

use Apex\Svc\{Dispatcher, MessageRequest};

 * Demo Class
class DemoClass

    private Dispatcher $dispatcher;

    * Send
    public function send(int $var1, string $var2, string $var3):void

        // Send message
        $msg = new MessageRequest('my-shop.orders.created', $var1, $var2, $var3);
    $res = $this->dispatcher->send($msg);

        // Get response
        $array_response = $res->getResponse();

        // Get response from specific package
        $package_response = $res->getResponse('some-specific-package');

The above example dispatches a message to the my-shop.orders.created routing key to inform all event listeners that action has just occurred. Any event listener with the my-shop.orders routing key will be instantiated, and the created method will be executed it one exists.

A response will be returned which can be obtained with the getResponse() method as shown above. The response is an array which contains one element for each package that contained an event listener listening on that routing key. If no argument is given to the getResponse() method, the full array will be returned, and otherwise only the response of the specific package will be returned.

For more information on dispatching messages, please visit the Dispatching Messages page of the Cluster documentation on Github.