Notifications¶
Nativella\Notification shows system notifications, on the desktop and on phones.
$notification->send('Export finished', 'notes.zip is in your Downloads folder.');
| Method | |
|---|---|
send(string $title, ?string $body = null, ?string $reference = null): void |
Shows a notification, with an optional body. |
send() returns as soon as the system has the notification, without waiting for the user.
On phones, the first notification asks the user whether to allow them, and send() waits for the answer, for up to 60 seconds, then throws a NativeCallException of the kind Timeout. Until the user answers, the next notifications throw the same Timeout right away, without asking again. When the user does not allow them, send() shows nothing and does not throw, as on macOS. After a first refusal, Android asks once more, on the next notification; after that, only the settings of the phone change the answer.
Clicks¶
A notification sent with a reference tells PHP when the user clicks it, with a Nativella\Event\NotificationClicked event that carries the reference:
$notification->send('New message', 'From Alice', reference: 'message-42');
use Nativella\Event\NotificationClicked;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
#[AsEventListener]
public function onClick(NotificationClicked $event): void
{
// $event->reference === 'message-42'
$this->window->open('main');
}
This is a Symfony listener. Lifecycle and events says how the other integrations route events.
Clicks are reported on Linux and macOS, for now. Windows shows the notification, but does not report the click. On macOS, a notification is the app's, with its name and its icon, and macOS asks the user whether to allow them on the first one. Under nativella run, which runs no app, it is the Terminal's.
On Linux, notifications go through the desktop's notification service (org.freedesktop.Notifications, on D-Bus), which every mainstream desktop provides.
A notification from a page¶
A notification needs no page change, and a fetch() from the page is enough. new Notification(), the browser API, shows nothing in a page, so a script injected in one cannot show system notifications. Only PHP can send them.
await fetch('/reminders/42/notify', { method: 'POST' });
// POST /reminders/{id}/notify
$notification->send('Reminder', $reminder->title);
http_response_code(204);
A notification from the background¶
PHP only runs when something asks it to: a request from a page, or a native event. A reminder "in ten minutes" is a timer: $timer->after('reminder-42', 600), then the notification from the TimerFired listener.