Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,221 of 9,224 pages
About the help in other languages
All help pages

Notifications for your extension

The kernel stores notifications per user (the tables expusernotif and expusernotif_delivery), shows them in the admin4 bell and the list page, and delivers them through channels. An extension emits a notification with…

Download as PDF

Address: https://doc.exponential.earth/exphelp/viewer/guides/user-notifications-developer.md

On this page

Notifications for your extension

The kernel stores notifications per user (the tables expusernotif and expusernotif_delivery), shows them in the admin4 bell and the list page, and delivers them through channels. An extension emits a notification with one call and registers a type that says how it reads. This guide shows both.

What you may rely on

WhatName
Feature detectionclass_exists( 'expUserNotificationService' ) (kernel autoload; no INI needed). Without it: keep the old behaviour, no notification code runs
EmitexpUserNotificationService::notify( string $type, int[] $recipientUserIds, array $data = [], array $options = [] ): expUserNotificationResult
Optionssource (string, the extension, e.g. newsletter), reference (string up to 100, e.g. edition:12), eventKey (string up to 64, idempotency), contentObjectId (int), actorId (int, excluded unless notifyActor), notifyActor (bool), outward (bool; only true lets the event go to chat, sms or push, missing means no), siteaccess (string)
ResultexpUserNotificationResult::storedIds(), queued(), skipped() (code per recipient/channel)
Type contractinterface expUserNotificationType; base class expUserNotificationBaseType (implement label(), title(), text(), url(), outwardText())
View passed to a typeexpUserNotificationView (viewerId(), state( $objectId ), objectName( $objectId ), mayLink( $objectId ), stateNote( $objectId )); a type's url() returns a path of this site with a leading / (/acme/order/12), anything else is dropped
Type registrationin the extension's settings/usernotification.ini.append.php: [Types] List[]=<id>, [Type_<id>] Class=..., MailCategory=...
Type naming<source>.<event>, lowercase, regex ^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$, up to 100 chars; newsletter uses newsletter.*
Default subscriptions[Subscriptions] Channels[<type>]=<channel>;<channel> in the extension's file; a site overrides per siteaccess
Channel namessystem, email, browser, log, chat, sms, push
Outward guard[Outward] Guards[<source>]=<Class>::<staticMethod> returning true to allow
Outward textoutwardText( array $event ): $event = type, source, reference, recipientCount, data, adminUrl; return a string with counts/ids/links only
Resolved subscriptions./console exp:usernotification:subscriptions -s <siteaccess>
Reference operations (additions)expUserNotificationService::markReadForReference( int $userId, string $source, string $reference ): int (call when the user opens the object's page), removeForReference( string $source, string $reference ): int (call when the object is deleted)
Filters (additions)find()/count() filter key source; markAllRead( int $userId, array $filter = [] ) with keys type, source
Template fetchfetch( 'usernotification', 'notices', hash( 'limit', n, 'state', 'unread'|'read'|'all', 'type', ..., 'source', ... ) ) returns rows id, type, source, reference, created, read, title, text, url, label; fetch( 'usernotification', 'unread_count' )
Bell and feedthe kernel bell usernotification/header_bell.tpl (one HeaderItems[] entry) and feed ezjscore/call/usernotification::notices::<n>; an extension adds no bell of its own for notifications
When to notifythe source decides; the kernel has no per-type "notify when" setting

A worked type

A type turns the stored ids and numbers into text when a notification is shown. It never reads a stored text: the data array holds ids and counts only.

class acmeOrderShippedType extends expUserNotificationBaseType
{
    function label()
    {
        return ezpI18n::tr( 'acme/notification', 'Order shipped' );
    }

    function title( $notification, $view )
    {
        $data = $notification->dataArray();
        return ezpI18n::tr( 'acme/notification', 'Order %number was shipped', null, array( '%number' => (int)$data['order'] ) );
    }

    function text( $notification, $view )
    {
        $data = $notification->dataArray();
        return ezpI18n::tr( 'acme/notification', '%count items', null, array( '%count' => (int)$data['items'] ) );
    }

    function url( $notification, $view )
    {
        $data = $notification->dataArray();
        return '/acme/order/' . (int)$data['order'];
    }

    function outwardText( array $event )
    {
        return 'Order shipped: ' . (int)$event['data']['order'] . ' ' . $event['adminUrl'];
    }
}

Register it in extension/acme/settings/usernotification.ini.append.php:

<?php /* #?ini charset="utf-8"?

[Types]
List[]=acme.order_shipped

[Type_acme.order_shipped]
Class=acmeOrderShippedType
MailCategory=system

[Subscriptions]
Channels[acme.order_shipped]=system;email

*/ ?>

Emit it where the event happens:

if ( class_exists( 'expUserNotificationService' ) )
{
    expUserNotificationService::notify( 'acme.order_shipped', $assigneeIds,
        array( 'order' => $orderId, 'items' => $count ),
        array( 'source' => 'acme', 'reference' => 'order:' . $orderId, 'eventKey' => 'shipped:' . $orderId ) );
}

notify() never throws into your code: an unknown type or a database error is logged and answered by an empty result. Pass an eventKey when the code can run twice for one event (a retried job): a notification with the same owner, type and key is stored once.

The naming rule

A type id is <source>.<event>: lowercase, starting with a letter, parts separated by dots, up to 100 characters (^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$). The first part is your extension (source), so the list page can filter by it.

Feature detection

Your extension may run on a kernel without notifications. Wrap every call in class_exists( 'expUserNotificationService' ) and keep the old behaviour in the else case; with the class missing, no notification code runs.

The source decides when to notify

The kernel has no per-type "notify when" setting. Whether an event is worth a notification is a decision of the extension that knows the event, and it makes the decision before it calls expUserNotificationService::notify.

The import extension sqliimport shows the pattern: each import has a setting with the values never, failed, errors and always. When a run ends, the importer compares the setting with the run's outcome and calls the service only if the outcome qualifies (failed: the run failed; errors: it finished with errors or failed; always: every run; never: no call at all). The user's own preferences (which channels, which types) are applied afterwards by the kernel through the subscriptions.

Notifications about an object: reference calls

Pass source (your extension) and reference (the object the event is about, for example run:42) in the options of notify(). Two calls keep the notifications in step with the object:

  • expUserNotificationService::markReadForReference( $userId, $source, $reference ) marks the user's unread notifications of that object read. Make the call when the user opens the object's page. It changes only that user's rows and returns the number of rows changed.
  • expUserNotificationService::removeForReference( $source, $reference ) removes the notifications of that object for all owners, with their delivery rows. Make the call when your extension deletes the object. It returns the number of rows removed; an empty source or reference removes nothing.

Both never throw: on a database error (for example tables not upgraded yet) they log a warning and return 0. A retried job can pass the same eventKey (for example run:<id>) to notify(); a notification with the same owner, type and key is stored once.

For lists, find() and count() accept the filter key source, and markAllRead( $userId, $filter ) accepts the filter keys type and source to mark only those read. The read methods answer empty or 0 on a missing table.

Old rows

Read notifications are deleted after [Retention] ReadDays days, all notifications after AllDays days, and finished delivery rows after DeliveryDays days; 0 keeps that kind for good.

Moving an extension's own notices to the kernel

An extension that built its own notices (a table, a fetch, a feed and a bell) can move to the kernel service in a release of its own. The import extension sqliimport is the worked example. This section describes the path; the kernel does not change the package, and the one-off copy command below is described here, not shipped by the kernel.

Mapping the old pieces to the kernel

sqliimportkernel
expImportNotifier::addNotice( $run, $userId )expUserNotificationService::notify( 'sqliimport.run_ended', array( $userId ), array( 'run_id' => …, 'import_id' => …, 'kind' => … ), array( 'source' => 'sqliimport', 'reference' => 'run:<id>', 'eventKey' => 'run:<id>', 'notifyActor' => true ) ). notifyActor is set because the person who started the run is the intended recipient, even when the run ends in their own request
shouldNotify(), kindOf(), the import's notify settingsstay in sqliimport: the source decides when to notify (see above)
runEnded() never throwsunchanged; notify() does not throw either
mail() to the import's free addressesstays in sqliimport: the kernel's email channel mails accounts only. The starter's own mail can come from the email channel by subscription
expImportNotice, table sqliimport_noticeexpusernotif (column mapping below); the old table retires after the copy
notices( $userId, true, $n ), unseenCount()find( $userId, array( 'source' => 'sqliimport', 'state' => 'unread' ), 0, $n ) and count( $userId, array( 'source' => 'sqliimport', 'state' => 'unread' ) ) (not pendingCount(), which counts all sources); in templates fetch( 'usernotification', 'notices', hash( 'source', 'sqliimport', 'state', 'unread', 'limit', 5 ) )
markSeen( $userId, $runId ) on the run pagemarkReadForReference( $userId, 'sqliimport', 'run:<id>' )
markSeen( $userId, 0 ) ("Mark all as read")markAllRead( $userId, array( 'source' => 'sqliimport' ) )
removeForRun( $runId ) on purgeremoveForReference( 'sqliimport', 'run:<id>' )
fetch( 'sqliimport', 'notices' ), feed sqliimport::notices, header_bell.tplthe kernel's fetch fetch( 'usernotification', 'notices' ), the feed usernotification::notices and the bell usernotification/header_bell.tpl
a renderera type class expImportRunEndedType extends expUserNotificationBaseType: title "Run #n · import" for the viewer, url /sqliimport/run/<id>, outwardText() with ids and counts only. Register it in the package's settings/usernotification.ini.append.php with Channels[sqliimport.run_ended]=system as default

Mapping the old table to expusernotif

sqliimport_noticeexpusernotifNote
idnot keptthe copy gets new ids; nothing refers to a notice id from outside
user_idowner_id
run_idreference run:<run_id>, event_key run:<run_id>with source sqliimport: once per run and user
import_iddata import_id
kind (failed, errors, completed, cancelled)type sqliimport.run_ended, data kindone type; the kind is data the renderer shows
createdcreated
seenis_pending = 1 − seen; read_at = created when seenthe real read time is unknown
nonecontentobject_id 0, listed 1, browser_pending 0, source sqliimporta run is not a content object

Running on older kernels

Decide once per request, in a small adapter of the package:

$useKernel = class_exists( 'expUserNotificationService' )
    && in_array( 'expusernotif', eZDB::instance()->eZTableList(), true );

Without the class everything stays as it was: own table, own fetch, own feed, own bell. With the class but without the table (the code is deployed, exp:upgrade --apply has not run yet) the package keeps writing its own table, so no notice is lost between deploy and upgrade. With both, it writes and reads only through the kernel.

One bell, never two

The package's bell template tests HeaderItems for usernotification/header_bell.tpl and prints nothing when the kernel's bell is registered and the user has the policy usernotification/use. A user who may see the imports but not the kernel's bell keeps the package's bell, which then reads the kernel's notifications through the package's feed. A later major release of the package drops its HeaderItems entry.

Copying the existing rows

A one-off command of the package, for example ./console ext:sqliimport:migrate-notices -s <admin siteaccess> [--apply]:

  • It reports what it would do and changes nothing without --apply.
  • For each sqliimport_notice row it creates a notification with the mapping above, unless a row with the same owner, type and event key exists. It is idempotent by (owner, type, event key) and can run twice.
  • It names its siteaccess in the output and says that it looked at no other.
  • It leaves sqliimport_notice in place, so a rollback is possible; a later package release drops the table.

What stays with the source

When to notify stays with the source: sqliimport keeps its never, failed, errors and always settings and calls notify() only when the outcome qualifies.

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x