Examples

E-Commerce: Order Shipped

<?php

declare(strict_types=1);

namespace App\Notifications;

use WPZylos\Framework\Notification\Notification;
use WPZylos\Framework\Notification\MailMessage;
use WPZylos\Framework\Notification\AdminNoticeMessage;

class OrderShipped extends Notification
{
    public function __construct(
        private object $order,
        private string $trackingNumber
    ) {}

    public function via(): array
    {
        return ['mail', 'database', 'admin_notice'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage())
            ->subject('Your Order #' . $this->order->id . ' Has Shipped!')
            ->greeting('Great news, ' . $notifiable->name . '!')
            ->line('Your order has been shipped and is on its way.')
            ->line('Tracking number: ' . $this->trackingNumber)
            ->action('Track Your Package', 'https://example.com/track/' . $this->trackingNumber)
            ->level('success');
    }

    public function toDatabase(object $notifiable): array
    {
        return [
            'order_id'        => $this->order->id,
            'tracking_number' => $this->trackingNumber,
            'message'         => 'Order #' . $this->order->id . ' has been shipped.',
            'url'             => '/orders/' . $this->order->id,
        ];
    }

    public function toAdminNotice(object $notifiable): AdminNoticeMessage
    {
        return (new AdminNoticeMessage())
            ->message('Order #' . $this->order->id . ' shipped to ' . $notifiable->name)
            ->type('success');
    }
}

// Usage:
$customer->notify(new OrderShipped($order, 'TRACK-123456'));

User Registration Welcome

<?php

declare(strict_types=1);

namespace App\Notifications;

use WPZylos\Framework\Notification\Notification;
use WPZylos\Framework\Notification\MailMessage;

class WelcomeUser extends Notification
{
    public function __construct(private string $activationUrl) {}

    public function via(): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage())
            ->subject('Welcome to Our Platform!')
            ->greeting('Hello ' . $notifiable->name . '!')
            ->line('Thank you for creating an account.')
            ->line('Please click the button below to activate your account.')
            ->action('Activate Account', $this->activationUrl)
            ->level('info');
    }
}

Payment Failed (Error Notification)

<?php

declare(strict_types=1);

namespace App\Notifications;

use WPZylos\Framework\Notification\Notification;
use WPZylos\Framework\Notification\MailMessage;
use WPZylos\Framework\Notification\AdminNoticeMessage;

class PaymentFailed extends Notification
{
    public function __construct(
        private object $invoice,
        private string $errorMessage
    ) {}

    public function via(): array
    {
        return ['mail', 'database', 'admin_notice'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage())
            ->subject('Payment Failed — Invoice #' . $this->invoice->number)
            ->greeting('Payment Issue')
            ->line('We were unable to process your payment for invoice #' . $this->invoice->number . '.')
            ->line('Error: ' . $this->errorMessage)
            ->line('Please update your payment method and try again.')
            ->action('Update Payment', 'https://example.com/billing')
            ->level('error');
    }

    public function toDatabase(object $notifiable): array
    {
        return [
            'invoice_id' => $this->invoice->id,
            'error'      => $this->errorMessage,
            'message'    => 'Payment failed for invoice #' . $this->invoice->number,
        ];
    }

    public function toAdminNotice(object $notifiable): AdminNoticeMessage
    {
        return (new AdminNoticeMessage())
            ->message('**Warning:** Payment failed for invoice #' . $this->invoice->number . ': ' . $this->errorMessage)
            ->type('error')
            ->dismissible(false);
    }
}

Notification Inbox (Dashboard Page)

// In a WordPress admin page handler:
function render_notification_inbox(): void
{
    $user = get_current_user_model(); // your user-resolution logic

    $unread = $user->unreadNotifications();
    $read   = $user->readNotifications();

    echo '<h2>Notifications (' . count($unread) . ' unread)</h2>';

    foreach ($unread as $notification) {
        $data = json_decode($notification->data, true);
        echo '<div class="notification unread">';
        echo '<strong>' . esc_html($data['message'] ?? '') . '</strong>';
        echo '<br><small>' . esc_html($notification->created_at) . '</small>';
        echo '<form method="post"><input type="hidden" name="mark_read" value="' . (int) $notification->id . '">';
        echo '<button type="submit">Mark as Read</button></form>';
        echo '</div>';
    }

    foreach ($read as $notification) {
        $data = json_decode($notification->data, true);
        echo '<div class="notification read">';
        echo esc_html($data['message'] ?? '');
        echo '<br><small>Read: ' . esc_html($notification->read_at) . '</small>';
        echo '</div>';
    }
}

// Handle marking as read:
if (isset($_POST['mark_read'])) {
    $user->markNotificationAsRead((int) $_POST['mark_read']);
}

Custom Slack Channel

<?php

declare(strict_types=1);

namespace App\Channels;

use WPZylos\Framework\Notification\Contracts\NotificationChannel;
use WPZylos\Framework\Notification\Notification;

class SlackChannel implements NotificationChannel
{
    public function __construct(private string $webhookUrl) {}

    public function send(object $notifiable, Notification $notification): void
    {
        if (!method_exists($notification, 'toSlack')) {
            return;
        }

        $payload = $notification->toSlack($notifiable);

        wp_remote_post($this->webhookUrl, [
            'body'    => wp_json_encode($payload),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 5,
        ]);
    }
}

// Registration:
$manager->extend('slack', new SlackChannel('https://hooks.slack.com/services/...'));

// Notification using it:
class CriticalErrorNotification extends Notification
{
    public function __construct(private string $error) {}

    public function via(): array
    {
        return ['slack', 'admin_notice'];
    }

    public function toSlack(object $notifiable): array
    {
        return [
            'text'   => '🚨 Critical Error: ' . $this->error,
            'channel' => '#alerts',
        ];
    }

    public function toAdminNotice(object $notifiable): \WPZylos\Framework\Notification\AdminNoticeMessage
    {
        return (new \WPZylos\Framework\Notification\AdminNoticeMessage())
            ->message('Critical error detected: ' . $this->error)
            ->type('error')
            ->dismissible(false);
    }
}

Bulk Notification Sending

use WPZylos\Framework\Notification\NotificationManager;

$manager = $app->make(NotificationManager::class);

// Get all subscribers
$subscribers = $userRepository->findByRole('subscriber');

// Send a newsletter notification to all subscribers
$manager->send($subscribers, new NewsletterPublished($newsletter));

Conditional Channel Selection

class OrderStatusChanged extends Notification
{
    public function __construct(
        private object $order,
        private string $oldStatus,
        private string $newStatus
    ) {}

    public function via(): array
    {
        $channels = ['database'];

        // Only email for important status changes
        if (in_array($this->newStatus, ['shipped', 'delivered', 'refunded'])) {
            $channels[] = 'mail';
        }

        // Admin notice for cancellations
        if ($this->newStatus === 'cancelled') {
            $channels[] = 'admin_notice';
        }

        return $channels;
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage())
            ->subject('Order #' . $this->order->id . ' — ' . ucfirst($this->newStatus))
            ->greeting('Hi ' . $notifiable->name . '!')
            ->line('Your order status has changed from ' . $this->oldStatus . ' to ' . $this->newStatus . '.');
    }

    public function toDatabase(object $notifiable): array
    {
        return [
            'order_id'   => $this->order->id,
            'old_status' => $this->oldStatus,
            'new_status' => $this->newStatus,
        ];
    }
}