borsaco/pushe-notification-bundle
Installation
Run composer require borsaco/pushe-notification-bundle in your Symfony project root.
Ensure your composer.json includes the package under require.
Bundle Registration
Add the bundle to AppKernel.php:
public function registerBundles()
{
$bundles = [
// ...
new Borsaco\PusheNotificationBundle\PusheNotificationBundle(),
];
}
Configuration
Add your Pushe.co API token to config/packages/pushe_notification.yaml:
pushe_notification:
token: "%env(PUSHE_TOKEN)%" # Recommended: Use env vars for security
(Optional) Enable environment variables in .env:
PUSHE_TOKEN=your_token_here
First Notification Inject the service into a controller or command:
use Borsaco\PusheNotificationBundle\Service\PusheNotification;
class MyController extends AbstractController
{
public function __construct(private PusheNotification $pushe)
{}
public function sendNotification()
{
$this->pushe->send([
'message' => 'Hello from Symfony!',
'targets' => ['device_token_1', 'device_token_2'],
]);
}
}
Sending Notifications
Use the send() method with an associative array:
$this->pushe->send([
'message' => 'Your order is confirmed!',
'title' => 'Order Update',
'targets' => ['token1', 'token2'], // Array of device tokens
'data' => ['key' => 'value'], // Optional custom payload
]);
Batch Processing For large lists of devices, chunk targets to avoid API rate limits:
$batchSize = 100;
$devices = DeviceToken::all()->pluck('token');
foreach (array_chunk($devices, $batchSize) as $chunk) {
$this->pushe->send(['message' => 'Batch update', 'targets' => $chunk]);
}
Event-Driven Notifications
Trigger notifications from Symfony events (e.g., KernelEvents::TERMINATE):
// src/EventListener/NotificationListener.php
class NotificationListener implements EventSubscriber
{
public function onKernelTerminate(GetResponseEvent $event)
{
if ($event->getRequest()->isXmlHttpRequest()) {
$this->pushe->send(['message' => 'Request processed', 'targets' => [...]]);
}
}
}
Dependency Injection Prefer constructor injection over container access:
// Correct (recommended)
public function __construct(private PusheNotification $pushe) {}
// Avoid (legacy)
$this->container->get('pushe_notification');
Symfony Messenger Decouple notifications by dispatching messages:
// src/Message/SendPusheNotification.php
class SendPusheNotification implements MessageInterface
{
public string $message;
public array $targets;
}
// Worker
$bus->dispatch(new SendPusheNotification('Hello', ['token1']));
Doctrine Events Send notifications on entity lifecycle events:
// src/EventSubscriber/OrderSubscriber.php
class OrderSubscriber implements EventSubscriber
{
public function postPersist(Order $order)
{
$this->pushe->send([
'message' => 'New order #'.$order->id,
'targets' => $order->user->deviceTokens,
]);
}
}
Translation Support Use Symfony’s translation system for localized messages:
$this->pushe->send([
'message' => $this->translator->trans('notification.order.confirmed'),
'targets' => [...],
]);
Logging Wrap calls in a try-catch to log failures:
try {
$this->pushe->send([...]);
} catch (\Exception $e) {
$this->logger->error('Pushe notification failed', ['error' => $e->getMessage()]);
}
Token Security
.env or Symfony’s parameter_bag.$response = $this->pushe->send([...]);
$this->logger->debug('Pushe response', ['status' => $response->getStatusCode()]);
Rate Limits
$attempts = 0;
while ($attempts < 3) {
try {
$this->pushe->send([...]);
break;
} catch (RateLimitException $e) {
sleep(2 ** $attempts); // Exponential delay
$attempts++;
}
}
Device Token Management
// Pseudocode: Validate tokens via Pushe API
$validTokens = array_filter($deviceTokens, fn($token) => $this->pushe->validateToken($token));
Payload Size Limits
$longMessage = str_repeat('a', 5000);
$this->pushe->send(['message' => $longMessage]); // May be truncated
Enable API Debugging Add a debug endpoint to log raw API calls:
// src/Controller/PusheDebugController.php
class PusheDebugController extends AbstractController
{
public function debug(PusheNotification $pushe)
{
$pushe->setDebug(true); // Enable debug mode
$pushe->send(['message' => 'Debug test', 'targets' => [...]]);
return $this->json($pushe->getLastResponse());
}
}
Common Errors
| Error | Cause | Solution |
|---|---|---|
Invalid token |
Wrong API token | Check .env and Pushe dashboard |
No targets provided |
Empty targets array |
Validate input data |
HTTP 429 Too Many Requests |
Rate limit exceeded | Implement retries/backoff |
HTTP 500 Internal Server Error |
Pushe API issue | Check Pushe status page |
Custom Response Handling Extend the service to parse Pushe’s response:
// src/Service/ExtendedPusheNotification.php
class ExtendedPusheNotification extends PusheNotification
{
public function send(array $data): array
{
$response = parent::send($data);
return json_decode($response->getBody(), true);
}
}
Webhook Integration Use Pushe’s webhook feature to trigger Symfony events:
// src/EventListener/PusheWebhookListener.php
class PusheWebhookListener
{
public function onPusheWebhook(Request $request)
{
$data = json_decode($request->getContent(), true);
if ($data['event'] === 'delivery_receipt') {
$this->handleDelivery($data['device_token']);
}
}
}
Testing Mock the service in PHPUnit:
$mock = $this->createMock(PusheNotification::class);
$mock->method('send')->willReturn(new Response('{"success":true}'));
$controller = new MyController($mock);
$controller->sendNotification();
Configuration Overrides Dynamically override the token per environment:
# config/packages/dev/pushe_notification.yaml
pushe_notification:
token: "%env(PUSHE_TOKEN_DEV)%"
How can I help you explore Laravel packages today?