Weave Code
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

Platform Notification Bundle Laravel Package

digitalstate/platform-notification-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle to your `composer.json`:
   ```bash
   composer require digitalstate/platform-notification-bundle

Register the bundle in config/bundles.php (if not auto-discovered):

return [
    // ...
    DigitalState\PlatformNotificationBundle\DigitalStatePlatformNotificationBundle::class => ['all' => true],
];
  1. Database Migrations Run migrations to create the notification and subscription tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  2. First Use Case: Creating a Notification Inject the NotificationManager service and create a notification:

    use DigitalState\PlatformNotificationBundle\Entity\Notification;
    use DigitalState\PlatformNotificationBundle\Manager\NotificationManager;
    
    public function createNotification(NotificationManager $notificationManager)
    {
        $notification = new Notification();
        $notification->setTitle('Urgent Update');
        $notification->setMessage('This is a critical system update.');
        $notification->setChannel('email'); // 'email', 'sms', 'letter_mail', etc.
    
        $notificationManager->save($notification);
    }
    
  3. First Use Case: Subscribing a User Subscribe a user (e.g., User entity) to a notification topic:

    use DigitalState\PlatformNotificationBundle\Entity\Subscription;
    use DigitalState\PlatformNotificationBundle\Manager\SubscriptionManager;
    
    public function subscribeUser(SubscriptionManager $subscriptionManager, User $user, Notification $notification)
    {
        $subscription = new Subscription();
        $subscription->setUser($user);
        $subscription->setNotification($notification);
        $subscription->setChannel('email');
        $subscription->setIsActive(true);
    
        $subscriptionManager->save($subscription);
    }
    
  4. Where to Look First

    • Entities: src/Entity/Notification.php and src/Entity/Subscription.php for field definitions and relationships.
    • Managers: src/Manager/NotificationManager.php and src/Manager/SubscriptionManager.php for CRUD operations.
    • Services: src/Service/NotificationService.php for business logic (e.g., sending notifications).
    • Forms: src/Form/ for pre-built forms (if available) to manage notifications/subscriptions via admin panels.

Implementation Patterns

Core Workflows

1. Notification Creation and Management

  • Workflow:
    1. Create a Notification entity with metadata (title, message, channel, priority, etc.).
    2. Use NotificationManager to persist or update the notification.
    3. Optionally, associate metadata (e.g., tags, categories) via custom fields or extensions.
  • Example:
    $notification = (new Notification())
        ->setTitle('New Policy Announcement')
        ->setMessage('Details: [link]')
        ->setChannel('email')
        ->setPriority(Notification::PRIORITY_HIGH)
        ->setIsUrgent(true);
    
    $notificationManager->save($notification);
    

2. Subscription Handling

  • Workflow:
    1. Subscribe a user to a notification topic via SubscriptionManager.
    2. Track active/inactive subscriptions and channels (e.g., email, SMS).
    3. Use SubscriptionRepository to query subscriptions (e.g., find all active email subscriptions for a user).
  • Example:
    $subscription = (new Subscription())
        ->setUser($user)
        ->setNotification($notification)
        ->setChannel('sms')
        ->setIsActive(true);
    
    $subscriptionManager->save($subscription);
    

3. Sending Notifications

  • Workflow:
    1. Use NotificationService to trigger notifications for subscribed users.
    2. Implement channel-specific logic (e.g., email via Swiftmailer, SMS via Twilio).
    3. Log delivery status and handle failures (e.g., retries, dead-letter queues).
  • Example:
    $notificationService->send($notification, ['email', 'sms']);
    

4. Admin Panel Integration

  • Workflow:
    1. Extend OroPlatform’s grid/listing system to display notifications/subscriptions.
    2. Use pre-built forms (if available) or create custom ones for CRUD operations.
    3. Add filters/sorters to the admin grid (e.g., by channel, priority, or user).
  • Example Grid Configuration:
    # config/oro_platform_notification.yml
    oro_platform_notification:
        grid:
            notification:
                columns:
                    title: ~
                    channel: ~
                    priority: ~
                filters:
                    channel: ~
    

5. Event-Driven Notifications

  • Workflow:
    1. Listen to domain events (e.g., UserRegisteredEvent) and trigger notifications.
    2. Use Symfony’s event dispatcher to decouple notification logic from business logic.
  • Example:
    // src/EventListener/NotificationListener.php
    public function onUserRegistered(UserRegisteredEvent $event)
    {
        $notification = $this->createWelcomeNotification($event->getUser());
        $this->notificationService->send($notification, ['email']);
    }
    

Integration Tips

OroPlatform Integration

  • Leverage Oro’s EntityConfig system to customize notification/subscription fields (e.g., add custom attributes).
  • Use Oro’s Datagrid and DatagridHelper to build admin interfaces for notifications.

Channel-Specific Logic

  • Extend the NotificationService to support custom channels (e.g., push notifications, Slack).
  • Implement a ChannelInterface and register it as a service:
    class SlackChannel implements ChannelInterface
    {
        public function send(Notification $notification, User $user): void
        {
            // Logic to send via Slack
        }
    }
    

Testing

  • Use NotificationManager and SubscriptionManager in unit tests to verify CRUD operations.
  • Mock NotificationService to test sending logic without actual deliveries.

Gotchas and Tips

Pitfalls

1. Missing Channel Configuration

  • Issue: Not all channels (e.g., letter_mail) may be supported out-of-the-box.
  • Fix: Implement custom channel services or extend the bundle’s channel registry.

2. Subscription Overlap

  • Issue: Users may subscribe to the same notification multiple times (e.g., same user + notification + channel).
  • Fix: Add a unique constraint in the database or validate in SubscriptionManager:
    $existing = $subscriptionRepository->findOneBy([
        'user' => $user->getId(),
        'notification' => $notification->getId(),
        'channel' => $channel,
    ]);
    if ($existing) { /* Handle duplicate */ }
    

3. Performance with Large Subscriptions

  • Issue: Querying all subscriptions for a user may be slow if the table grows.
  • Fix: Add indexes to user_id, notification_id, and channel columns. Use pagination in admin grids.

4. Event Dispatching

  • Issue: Notifications may not trigger if events aren’t dispatched properly.
  • Fix: Verify event listeners are tagged correctly in services.yaml:
    services:
        App\EventListener\NotificationListener:
            tags:
                - { name: kernel.event_listener, event: user.registered, method: onUserRegistered }
    

5. Translation Strings

  • Issue: Hardcoded strings in notifications may not support localization.
  • Fix: Use Symfony’s translation system:
    $notification->setMessage($this->translator->trans('notification.welcome.message'));
    

Debugging Tips

1. Check Database Schema

  • Verify migrations were run and tables exist:
    php bin/console doctrine:schema:validate
    

2. Enable Debugging for Events

  • Temporarily log dispatched events to ensure listeners are triggered:
    // In a listener
    error_log('Event triggered: ' . $event->getName());
    

3. Validate Entity States

  • Use isModified() or isNew() to debug entity changes:
    if ($notification->isModified()) {
        error_log('Modified fields: ' . implode(', ', $notification->getModifiedFields()));
    }
    

4. Channel-Specific Errors

  • Log failures in custom channel services to identify issues (e.g., API timeouts for SMS):
    try {
        $this->smsGateway->send($message);
    } catch (\Exception $e) {
        error_log('SMS failed: ' . $e->getMessage());
        // Implement retry logic
    }
    

Extension Points

1. Custom Notification Types

  • Extend the Notification entity or use inheritance to add domain-specific fields:
    class Policy
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor