Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Notification Bundle Laravel Package

ack/notification-bundle

Symfony bundle providing a Redis + Node.js (socket.io) pub/sub notification architecture. Render notifications via Twig, publish to specific user IDs or everyone, track online users in Redis, and push real-time “notification” events to connected clients.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ack/notification-bundle
    

    Register the bundle in AppKernel.php:

    new Ack\NotificationBundle\AckNotificationBundle(),
    
  2. Redis & Node.js Server

    • Ensure Redis is running (redis-server).
    • Navigate to /web/bundles/acknotification/nodejs and run:
      npm install
      node server.js
      
    • Verify the Node server is running on port 1337 (default).
  3. First Notification In a controller, inject and use the ack.notifier service:

    $this->get('ack.notifier')->notify(
        ':notification:test.html.twig', // Path to Twig template
        [1, 2, 3],                       // User IDs to notify
        ['param' => 'value']            // Optional template variables
    );
    
  4. Frontend Integration Include Socket.IO in your layout:

    <script src="http://your.domain:1337/socket.io/socket.io.js"></script>
    <script src="/bundles/acknotification/js/notifications.js"></script>
    

Implementation Patterns

Core Workflow

  1. Publish Notifications Use the ack.notifier service to dispatch notifications from anywhere in the app (controllers, services, commands):

    $notifier = $this->get('ack.notifier');
    $notifier->notify(':notification:alert.html.twig', [userId], ['urgent' => true]);
    
  2. Template Design

    • Store Twig templates in :notification: namespace (e.g., Resources/views/notification/alert.html.twig).
    • Use {{ content }} in templates to render dynamic content passed via the 3rd argument of notify().
  3. User-Specific Logic

    • Target specific users with arrays of IDs (e.g., [1, 2, 3]).
    • Broadcast to all users (including anonymous) with '*'.
  4. Frontend Handling Extend notifications.js to customize how notifications appear:

    $(document).ready(function() {
        var socket = io.connect('http://your.domain:1337');
        socket.on('notification', function(data) {
            // Custom logic (e.g., show toast, update UI)
            console.log('New notification:', data);
        });
    });
    

Advanced Patterns

  • Conditional Notifications Use services to filter users dynamically:

    $userIds = $userService->getActiveUsers();
    $notifier->notify(':notification:update.html.twig', $userIds);
    
  • Background Processing Dispatch notifications asynchronously via Symfony’s Messenger or queues (if extended).

  • Notification Types Group templates by type (e.g., :notification:email/, :notification:push/), then route accordingly in the Node server.


Gotchas and Tips

Common Pitfalls

  1. Redis Connection Issues

    • Ensure Redis is running and accessible. Configure the bundle’s redis_host in config.yml if needed:
      ack_notification:
          redis_host: 127.0.0.1
          redis_port: 6379
      
    • Debug with redis-cli PING and check Node server logs for connection errors.
  2. Node Server Crashes

    • Monitor the Node process (ps aux | grep node). Restart with:
      pm2 start server.js --name ack-notification
      
    • Handle unhandled exceptions in server.js:
      process.on('uncaughtException', function(err) {
          console.error('Node error:', err);
      });
      
  3. Twig Template Paths

    • Gotcha: Paths must start with :notification: (e.g., :notification:test.html.twig). Relative paths (e.g., notification/test.html.twig) will fail.
    • Fix: Use absolute paths or configure the Twig loader in the bundle.
  4. CORS Restrictions

    • If Socket.IO fails to connect, ensure your Node server allows requests from your domain:
      io.set('origins', 'http://your.domain:*');
      

Debugging Tips

  • Log Notifications Extend the Node server to log published messages:

    socket.on('notification', function(data) {
        console.log('Sent to users:', data.users, 'Content:', data.content);
    });
    
  • Check Redis Channels Use redis-cli MONITOR to verify messages are published to the correct channel (default: ack_notification).

  • Frontend Debugging Inspect network requests in DevTools (socket.io tab) to confirm messages are received.

Extension Points

  1. Custom Node Server Override server.js to add features (e.g., rate limiting, authentication):

    // Example: Filter notifications by user role
    socket.on('notification', function(data) {
        if (data.users.includes('*') || userService.isAdmin(data.users[0])) {
            io.to(data.users).emit('notification', data);
        }
    });
    
  2. Multiple Notification Types Extend the bundle to support different channels (e.g., WebSocket, Firebase):

    // In a custom service
    $notifier->notify('firebase', ':notification:push.html.twig', [1, 2]);
    
  3. Symfony Messenger Integration Create a custom transport to decouple notifications from the controller layer:

    // config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                notification: '%env(MESSENGER_TRANSPORT_DSN)%'
            routing:
                'App\Message\NotificationMessage': notification
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log