Publish from your module

This page is for version 1.1. Read the current version.

For arlanix/notification 1.1.0

Publish from your module

Your module can publish a message to a topic when something happens. The store chooses the topic in your module's settings. The topic's subscriptions decide who receives the message.

A module can send notifications in two ways:

  • Publish a message itself, as this page explains. Use this when your module's own settings decide what is sent, for example the failure alerts of an export.
  • Declare events. The store's rules then decide what is sent, when, and to which topic, in the same way as for a new order.

The message

A message has the following fields:

Field Type Description
subject string One line. Line breaks and repeated spaces become one space. The maximum is 255 characters. A longer subject is cut and ends with ….
body string Plain text. The maximum is 65,536 characters. A longer body is cut in the same way.
severity info, warning or error Any other value becomes info. Each subscription receives all messages, only warnings and errors, or only errors.
attributes array<string, scalar> Short details shown with the message, in the order you give them, for example ['Export' => 'orders-nightly']. The limits are 50 attributes, 64 characters for a label and 1,024 characters for a value. true and false are shown as yes and no. An array, an object, null, an empty label or an empty value is skipped.
source string The name of your module, for example Vendor_Module, up to 128 characters. The Message Log shows it.
details bool true by default. With true, the attributes, the topic, the source and the time are shown below the body. With false, only the subject and the body are sent. Use false when the body already says everything.

Your module decides when something is worth a message. Publish when a state changes, for example when an export starts to fail, and again when it works. Do not publish on every run. If you publish the same message again while an earlier copy still waits for delivery, the digest shows it once, with a count. A message that you publish every minute is still sent every minute.

With the module required

To publish with the module's classes, follow these steps:

  1. Add arlanix/module-notification to require in your composer.json.
  2. Add Arlanix_Notification to the <sequence> in your etc/module.xml.
  3. Inject PublisherInterface and MessageInterfaceFactory, and call publish():
use Arlanix\Notification\Api\Data\MessageInterfaceFactory;
use Arlanix\Notification\Api\PublisherInterface;

public function __construct(
    private readonly PublisherInterface $publisher,
    private readonly MessageInterfaceFactory $messageFactory
) {
}

public function announce(int $topicId, string $export, string $reason): void
{
    $this->publisher->publish($topicId, $this->messageFactory->create([
        'subject' => sprintf('Export %s failed', $export),
        'body' => $reason,
        'severity' => 'error',
        'attributes' => ['Export' => $export],
        'source' => 'Vendor_Module',
    ]));
}

publish() returns the number of deliveries it queued. It never throws. When something goes wrong, it writes the problem to the log, and your code continues:

  • A topic that does not exist is logged as a warning.
  • A topic that is switched off is logged as info.
  • Any other failure is logged as an error.

publish() writes to the database and to the message queue. It does not wait for a mail server or a chat service, unless you send the message immediately. See Send without the queue.

If you call publish() inside a database transaction, the message is saved in that transaction. Its deliveries go to the queue after the commit. If the transaction is rolled back, the message is removed and nothing is sent. To report the failure that caused a rollback, publish after the rollback.

Send without the queue

To send a message immediately, pass true as the third argument, $immediate:

$this->publisher->publish($topicId, $message, true);

The message is then sent in the same PHP process, not through the queue. Inside a transaction, sending starts after the commit. publish() waits for each subscription's mail server or chat service. It waits up to 10 seconds for a chat service, and up to the Timeout (seconds) setting for an SMTP server, which is also 10 by default.

Use this only for a message about a problem that stops the queue itself, such as monitoring's Cron stopped. If an immediate delivery fails, cron retries it like any other delivery.

A declared event can do the same with immediate="true". See Declare events. The arlanix_notification_publish event always uses the queue.

With the module only suggested

If your module only suggests Multichannel Store Notifications, add it under suggest in your composer.json. Then publish by dispatching the arlanix_notification_publish event. This needs none of the module's classes:

$this->eventManager->dispatch('arlanix_notification_publish', [
    'topic_id' => $topicId,
    'subject' => sprintf('Export %s failed', $export),
    'body' => $reason,
    'severity' => 'error',
    'attributes' => ['Export' => $export],
    'source' => 'Vendor_Module',
]);

The event works as follows:

  • If Multichannel Store Notifications is not installed, nothing listens to the event, and nothing happens.
  • An empty or 0 topic_id publishes nothing. A topic select left on -- Do not send -- saves an empty value.
  • The event accepts every field of the message except details. A message published through the event always shows its details.

The topic setting

The store creates the topics, so your module needs a setting where the store chooses one.

If your module requires Multichannel Store Notifications, use its source model in system.xml:

<field id="alerts_topic" translate="label" type="select" sortOrder="10" showInDefault="1">
    <label>Send alerts to topic</label>
    <source_model>Arlanix\Notification\Model\Source\TopicsOrNone</source_model>
</field>

TopicsOrNone lists -- Do not send -- first, and then every topic. A topic that is switched off is marked (switched off).

If your module only suggests Multichannel Store Notifications, do not name any of its classes. A missing class breaks the configuration page. Do the following instead:

  • Hide the field while the module is not installed, with <if_module_enabled>.
  • Use a source model of your own, which gets the topics from the arlanix_notification_topic_options event.

The field:

<field id="alerts_topic" translate="label" type="select" sortOrder="10" showInDefault="1">
    <label>Send alerts to topic</label>
    <source_model>Vendor\Module\Model\Source\NotificationTopics</source_model>
    <if_module_enabled>Arlanix_Notification</if_module_enabled>
</field>

The source model:

class NotificationTopics implements \Magento\Framework\Data\OptionSourceInterface
{
    public function __construct(private readonly \Magento\Framework\Event\ManagerInterface $eventManager)
    {
    }

    public function toOptionArray(): array
    {
        $transport = new \Magento\Framework\DataObject();
        $this->eventManager->dispatch('arlanix_notification_topic_options', ['transport' => $transport]);

        return [['value' => '', 'label' => __('-- Do not send --')], ...(array)$transport->getData('options')];
    }
}

From outside Magento

To publish from a script or a monitoring system, run bin/magento arlanix:notification:publish. See Queue, cron and command line.