Search…
The Web Push Service
The bundle provides a public Web Push service that you can inject this service into your application components.
In the following example, let's imagine that a notification is dispatched using the Symfony Messanger component and catched by an event handler. This handler will fetch all subscriptions and send the notification.
The SubscriptionRepository class is totally fictive
src/MessageHandler/SendNotification.php
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\MessageHandler;
6
7
use App\Message\SubscriptionExpired;
8
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
9
use Symfony\Component\Messenger\MessageBusInterface;
10
use WebPush\Notification;
11
use WebPush\WebPush;
12
13
final class SendPushNotifications implements MessageHandlerInterface
14
{
15
private MessageBusInterface $messageBus;
16
private SubscriptionRepository $repository;
17
private WebPush $webPush;
18
19
public function __construct(MessageBusInterface $messageBus, SubscriptionRepository $repository, WebPush $webPush)
20
{
21
$this->messageBus = $messageBus;
22
$this->repository = $repository;
23
$this->webPush = $webPush;
24
}
25
26
public function __invoke(Notification $notification): void
27
{
28
// Fetch all subscriptions
29
$subscriptions = $this->repository->fetchAllSubscriptions();
30
foreach ($subscriptions as $subscription) {
31
//Sends the notification to the subscriber
32
$report = $this->webPush->send($notification, $subscription);
33
34
//If the subscription expired
35
if ($report->subscriptionExpired()) {
36
//We dispatch a new message and expect for
37
// the subscription to be deleted
38
$this->messageBus->dispatch(
39
new SubscriptionExpired($subscription)
40
);
41
}
42
}
43
}
44
}
Copied!
Export as PDF
Copy link