PHP code example of tobento / app-notifier

1. Go to this page and download the library: Download tobento/app-notifier library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tobento / app-notifier example snippets


use Tobento\App\AppFactory;
use Tobento\App\Notifier\AvailableChannelsInterface;
use Tobento\App\Notifier\Formatting\NotificationFormattersInterface;
use Tobento\App\Notifier\GuestResolverInterface;
use Tobento\App\Notifier\NotificationsInterface;
use Tobento\App\Notifier\ReadNotificationResolverInterface;
use Tobento\Service\Notifier\ChannelsInterface;
use Tobento\Service\Notifier\NotifierInterface;
use Tobento\Service\Notifier\QueueHandlerInterface;

// Create the app
$app = new AppFactory()->createApp();

// Add directories:
$app->dirs()
    ->dir(realpath(__DIR__.'/../'), 'root')
    ->dir(realpath(__DIR__.'/../app/'), 'app')
    ->dir($app->dir('app').'config', 'config', group: 'config')
    ->dir($app->dir('root').'public', 'public')
    ->dir($app->dir('root').'vendor', 'vendor');

// Adding boots
$app->boot(\Tobento\App\Notifier\Boot\Notifier::class);
$app->booting();

// Service-related interfaces:
$notifier = $app->get(NotifierInterface::class);
$channels = $app->get(ChannelsInterface::class);
$queueHandler = $app->get(QueueHandlerInterface::class);

// App-related interfaces:
$availableChannels = $app->get(AvailableChannelsInterface::class);
$notificationFormatters = $app->get(NotificationFormattersInterface::class);
$notifications = $app->get(NotificationsInterface::class);
$guestResolver = $app->get(GuestResolverInterface::class);
$readNotificationResolver = $app->get(ReadNotificationResolverInterface::class);

// Run the app
$app->run();

use Tobento\App\Notifier\AvailableChannelsInterface;

$channels = $app->get(AvailableChannelsInterface::class);

// Check if a channel exists:
var_dump($channels->has(channel: 'sms'));
// bool(true)

// Get the title for a channel:
var_dump($channels->titleFor(channel: 'sms'));
// string(3) "Sms"

// Get all channel names:
var_dump($channels->names());
// array(3) {[0]=> string(4) "mail" [1]=> string(3) "sms" [2]=> string(7) "storage"}

// Get all channel titles:
var_dump($channels->titles());
// array(3) {[0]=> string(4) "Mail" [1]=> string(3) "Sms" [2]=> string(7) "Storage"}

// Convert titles to a string:
var_dump($channels->titlesToString(separator: ', '));
// string(18) "Mail, Sms, Storage"

// Add or override a channel title (returns a new instance):
$channels = $channels->withTitle(channel: 'sms', title: 'SMS Channel');
var_dump($channels->titleFor(channel: 'sms'));
// string(11) "SMS Channel"

// Map titles (returns a new instance):
$channels = $channels->map(fn($title, $name) => strtoupper($title));
var_dump($channels->titlesToString(separator: ', '));
// string(26) "MAIL, SMS CHANNEL, STORAGE"

// Sort channels by name (returns a new instance):
$channels = $channels->sortByName();

// Sort channels by title (returns a new instance):
$channels = $channels->sortByTitle();

// Count channels:
var_dump($channels->count());
// int(3)

// Keep only specific channels (returns a new instance):
$channels = $channels->only(['sms', 'mail']);

// Exclude specific channels (returns a new instance):
$channels = $channels->except(['sms', 'mail']);

// Iterate over channels:
foreach ($channels->all() as $name => $title) {}
// or simply:
foreach ($channels as $name => $title) {}

$user = $request->getAttribute(UserInterface::class);

'features' => [
    new Feature\Browser(
        // The browser channels to use for this feature.
        browserChannels: ['browser'],
        
        // If true, routes are localized (default: true).
        localizeRoute: false,
        
        // ACL is enabled by default.
        // Disable ACL checks only for testing.
        // When ACL is enabled (recommended for production), users must have
        // the 

$user = $request->getAttribute(UserInterface::class);

'features' => [
    new Feature\BrowserStream(
        // The browser channels to use for this feature.
        browserChannels: ['browser'],
        
        // If true, routes are localized (default: true).
        localizeRoute: false,
        
        // ACL is enabled by default.
        // Disable ACL checks only for testing.
        // When ACL is enabled (recommended for production), users must have
        // the 

'features' => [
    new Feature\BrowserGuest(
        // The browser channels to use for this feature.
        browserChannels: ['browser'],
        
        // The view 'notifier.browser.guest' is automatically rendered
        // when the specified view ('inc/head') is rendered.
        autoRenderOnView: 'inc/head',
        
        // You may disable auto rendering. If disabled, you must manually
        // 

'features' => [
    new Feature\BrowserView(
        // The browser channels to use for this feature.
        browserChannels: ['browser'],
        
        // The view 'notifier.browser' is automatically rendered
        // when the specified view ('inc/head') is rendered.
        autoRenderOnView: 'inc/head',
        
        // You may disable auto rendering. If disabled, you must manually
        // 

use Tobento\Service\Notifier\Notification;
use Tobento\Service\Notifier\NotifierInterface;
use Tobento\Service\Notifier\Recipient;

class SomeService
{
    public function send(NotifierInterface $notifier): void
    {
        // Create a Notification that has to be sent:
        // using the "email" and "sms" channel
        $notification = new Notification(
            subject: 'New Invoice',
            content: 'You got a new invoice for 15 EUR.',
            channels: ['mail', 'sms'],
        );

        // The receiver of the notification:
        $recipient = new Recipient(
            email: '[email protected]',
            phone: '15556666666',
        );

        // Send the notification to the recipient:
        $notifier->send($notification, $recipient);
    }
}

$app->boot(\Tobento\App\User\Boot\User::class);

use Psr\Http\Message\ServerRequestInterface;
use Tobento\App\User\UserInterface;
use Tobento\Service\Notifier\Notification;
use Tobento\Service\Notifier\NotifierInterface;
use Tobento\Service\Notifier\UserRecipient;

class SomeService
{
    public function send(NotifierInterface $notifier, ServerRequestInterface $request): void
    {
        // Create a Notification to be sent using multiple channels
        $notification = new Notification(
            subject: 'Thanks for your order',
            content: 'Your order has been received and is being processed.',
            channels: ['mail', 'sms', 'browser'],
        );
        
        // Get the current user (authenticated or guest):
        $user = $request->getAttribute(UserInterface::class);

        // Create the recipient for the current user:
        $recipient = new UserRecipient(user: $user);

        // Send the notification to the recipient:
        $notifier->send($notification, $recipient);
    }
}

use Tobento\App\Notifier\GuestResolverInterface;
use Tobento\Service\Notifier\GuestRecipient;
use Tobento\Service\Notifier\Notification;
use Tobento\Service\Notifier\NotifierInterface;

class SomeService
{
    public function send(NotifierInterface $notifier, GuestResolverInterface $guestResolver): void
    {
        // Create a Notification that has to be sent:
        // using the "browser" channel
        $notification = new Notification(
            subject: 'Special Offer',
            content: 'A new discount is available for you!',
            channels: ['browser'],
        );

        // Send to the current guest session:
        $recipient = new GuestRecipient(
            id: $guestResolver->resolveId(),
        );

        // Or send to all guest sessions:
        $recipient = new GuestRecipient(
            id: null,
        );

        // Send the notification to the recipient:
        $notifier->send($notification, $recipient);
    }
}

$notification = new Notification()
    ->addMessage('browser', new Message\Browser([
        'title' => 'Optional title',               // js-notifier: title
        'message' => 'You received a new order.',  // js-notifier: text
        'status' => 'warning',                     // js-notifier: status

        // Optional behavior
        'autotimeout' => 500,                      // js-notifier: autotimeout
        //'autotimeout' => null,                   // never closes
        'showCloseButton' => false,                // default: true

        // Action button
        'action_text' => 'View Order',             // js-notifier: action.title
        'action_route' => 'orders.view',           // js-notifier: action.url
        'action_route_parameters' => ['id' => 555],
        'action_attributes' => [                   // js-notifier: action.classes
            'class' => 'button',
        ],
    ]));

use Tobento\Service\Notifier\AbstractNotification;
use Tobento\Service\Notifier\Message;
use Tobento\Service\Notifier\RecipientInterface;

class SampleNotification extends AbstractNotification implements Message\ToBrowser
{
    /**
     * Returns the browser message.
     *
     * @param RecipientInterface $recipient
     * @param string $channel The channel name.
     * @return Message\BrowserInterface
     */
    public function toBrowser(RecipientInterface $recipient, string $channel): Message\BrowserInterface
    {
        return new Message\Browser(data: [
            'title' => 'Optional title',
            'message' => 'You received a new order.',
            'status' => 'warning',

            // Optional behavior
            'autotimeout' => 500,

            'action_text' => 'View Order',
            'action_route' => 'orders.view',
            'action_route_parameters' => ['id' => 555],
        ]);
    }
}

use Tobento\Service\Notifier\NotifierInterface;
use Tobento\Service\Notifier\Notification;
use Tobento\Service\Notifier\Recipient;
use Tobento\Service\Notifier\Parameter\Queue;

class SomeService
{
    public function send(NotifierInterface $notifier): void
    {
        // Create a Notification that has to be sent
        // using the "mail" and "sms" channels:
        $notification = new Notification(
            subject: 'New Invoice',
            content: 'You got a new invoice for 15 EUR.',
            channels: ['mail', 'sms'],
        )->parameter(new Queue(
            // You may specify the queue to be used:
            name: 'secondary',
            // You may specify a delay in seconds:
            delay: 30,
            // You may specify how many times to retry:
            retry: 3,
            // You may specify a priority:
            priority: 100,
            // You may specify if you want to encrypt the message:
            encrypt: true,
        ));

        // The receiver of the notification:
        $recipient = new Recipient(
            email: '[email protected]',
            phone: '15556666666',
        );

        // Send the notification to the recipient:
        $notifier->send($notification, $recipient);
    }
}

use Tobento\Service\Notifier\Message;
use Tobento\Service\Notifier\Notification;

// Storage
$notification = new Notification()
    ->addMessage('storage', new Message\Storage([
        'message' => 'You received a new order.',
        'action_text' => 'View Order',
        'action_route' => 'orders.view',
        'action_route_parameters' => ['id' => 555],
    ]));

// Browser
$notification = new Notification()
    ->addMessage('browser', new Message\Browser([
        'message' => 'You received a new order.',
        'action_text' => 'View Order',
        'action_route' => 'orders.view',
        'action_route_parameters' => ['id' => 555],
    ]));

'formatters' => [
    \Tobento\App\Notifier\Formatting\GeneralNotificationFormatter::class,
],

use Tobento\App\Notifier\Formatting\Notification;
use Tobento\App\Notifier\Formatting\NotificationFormatterInterface;

class GeneralNotificationFormatter implements NotificationFormatterInterface
{
    public function format(Notification $notification): Notification
    {
        // General data available:
        $id = $notification->id();
        $name = $notification->name();
        $recipientId = $notification->recipientId();
        $recipientType = $notification->recipientType();
        $readAt = $notification->get('read_at');
        $createdAt = $notification->get('created_at');
        $subject = $notification->get('data.subject', '');
        $content = $notification->get('data.content', '');
        
        // Format:
        return $notification
            ->withMessage($subject.': '.$content);
    }
}

'formatters' => [
    GeneralNotificationFormatter::class,
],

use Tobento\App\Notifier\Formatting\NotificationFormatterInterface;
use Tobento\App\Notifier\Formatting\Notification;
use Tobento\Service\Routing\RouterInterface;
use Tobento\Service\Translation\TranslatorInterface;

class NewOrderNotificationFormatter implements NotificationFormatterInterface
{
    public function __construct(
        protected TranslatorInterface $translator,
        protected RouterInterface $router,
    ) {}
    
    public function format(Notification $notification): Notification
    {
        // Only format specific notifications:
        if (!$notification->name() instanceof NewOrderNotification) {
            return $notification;
        }
        
        // Stop further formatters from modifying this notification:
        $notification->stopPropagation(true);
        
        // Retrieve specific message data:
        $orderId = $notification->get('data.order_id');
        
        // Format:
        return $notification
            ->withMessage($this->translator->trans('New order received'))
            ->withAddedAction(
                text: $this->translator->trans('View Order'),
                url: $this->router->url('orders.view', ['id' => $orderId]),
            );
    }
}

'formatters' => [
    NewOrderNotificationFormatter::class,
    GeneralNotificationFormatter::class,
],

use Tobento\Service\Notifier\NotificationInterface;
use Tobento\Service\Notifier\Parameter\Queue;

'notifications' => [
    // Using a custom notification:
    UserRegisterNotification::class => CustomUserRegisterNotification::class,
    
    // Using a notification factory:
    UserRegisterNotification::class => UserRegisterNotificationFactory::class,
    
    // Using a closure:
    UserRegisterNotification::class => function (UserRegisterNotification $notification): NotificationInterface {
        return $notification->parameter(new Queue());
    },
    
    // If named notification:
    'register' => CustomUserRegisterNotification::class,
],

use Tobento\Service\Notifier\AbstractNotification;
use Tobento\Service\Notifier\RecipientInterface;
use Tobento\Service\Notifier\Message;

class CustomUserRegisterNotification extends AbstractNotification implements Message\ToSms
{
    public function __construct(
        protected UserRegisterNotification $notification,
        // ...
    ) {}
    
    public function toSms(RecipientInterface $recipient, string $channel, SomeService $service): Message\SmsInterface
    {
        return new Message\Sms(
            subject: 'Thanks for your registration',
        );
    }
}

use Tobento\App\Notifier\NotificationFactoryInterface;
use Tobento\Service\Notifier\NotificationInterface;

class UserRegisterNotificationFactory implements NotificationFactoryInterface
{
    public function createNotification(NotificationInterface $notification): NotificationInterface
    {
        // create custom notification:
        
        // or modify original:
        return $notification;
    }
}

POST /{?locale}/notifications/browser

POST /{?locale}/notifications/browser-guest
app/config/notifier.php
app/config/notifier.php
app/config/notifier.php

php ap user:notifications:clear

php ap user:notifications:clear --channel=foo --channel=bar