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 Communication Bundle Laravel Package

digitalstate/platform-communication-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require digitalstate/platform-communication-bundle

Add to config/bundles.php:

return [
    // ...
    DigitalState\Platform\CommunicationBundle\DigitalStatePlatformCommunicationBundle::class => ['all' => true],
];
  1. Database Migrations: Run migrations to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  2. First Use Case: Create a basic email template via the admin interface (if available) or programmatically:

    use DigitalState\Platform\CommunicationBundle\Entity\Template;
    use DigitalState\Platform\CommunicationBundle\Entity\Channel;
    
    $channel = $entityManager->getRepository(Channel::class)->findOneBy(['type' => 'email']);
    $template = new Template();
    $template->setChannel($channel)
             ->setName('Welcome Email')
             ->setSubject('Welcome to Our Platform')
             ->setContent('Hello {{user}}, welcome!');
    $entityManager->persist($template);
    $entityManager->flush();
    

Implementation Patterns

Core Workflows

1. Template Management

  • Dynamic Content: Use placeholders (e.g., {{user}}) for dynamic content.
    $template->setContent('Your order {{orderId}} is confirmed.');
    
  • Channel-Specific Templates: Ensure templates are linked to a Channel entity (e.g., email, sms).
    $emailChannel = $entityManager->getRepository(Channel::class)->findOneBy(['type' => 'email']);
    $template->setChannel($emailChannel);
    

2. Message Generation

  • Query Builder Integration: Use the MessageQueryBuilder to filter messages by criteria.
    use DigitalState\Platform\CommunicationBundle\Query\MessageQueryBuilder;
    
    $queryBuilder = $entityManager->getRepository(Message::class)->createQueryBuilder('m');
    $queryBuilder->where('m.status = :status')
                 ->setParameter('status', 'draft');
    $messages = $queryBuilder->getQuery()->getResult();
    
  • Bulk Actions: Send messages in batches using Communication entity.
    $communication = new Communication();
    $communication->setTemplate($template)
                  ->setRecipients([$user1, $user2])
                  ->setChannel($channel);
    $entityManager->persist($communication);
    $entityManager->flush();
    

3. Criterion-Based Filtering

  • Dynamic Criteria: Use Criterion to filter recipients dynamically.
    $criterion = new Criterion();
    $criterion->setField('user.age')
              ->setOperator('>')
              ->setValue(18);
    $communication->addCriterion($criterion);
    

4. Content Management

  • Rich Content: Store HTML/Markdown in the Content entity for emails or inbox messages.
    $content = new Content();
    $content->setBody('<h1>Hello!</h1><p>This is a <strong>rich</strong> message.</p>');
    $template->setContent($content);
    

5. Integration with OroPlatform

  • Event Listeners: Extend functionality using OroPlatform events (e.g., oro_integration.connect).
    // Example: Trigger a communication on user registration
    public function onUserRegistered(UserRegisteredEvent $event)
    {
        $user = $event->getUser();
        $this->sendWelcomeEmail($user);
    }
    
  • Workflow Integration: Use OroPlatform workflows to automate message sending.
    # config/workflows/welcome_email.yml
    steps:
      - action: send_communication
        args:
          template: welcome_email
          recipients: [@user]
    

Gotchas and Tips

Pitfalls

  1. Channel Configuration:

    • Ensure channels (e.g., email, sms) are properly configured in the database. Missing channels will cause errors.
    • Fix: Run php bin/console oro:platform:install:channels (if available) or manually insert records into the channel table.
  2. Placeholder Parsing:

    • Incorrect placeholders (e.g., {{missing}}) will not render gracefully. Always validate placeholders before sending.
    • Tip: Use a helper method to validate placeholders:
      private function validatePlaceholders(string $content, array $data): bool
      {
          preg_match_all('/\{\{(\w+)\}\}/', $content, $matches);
          return array_diff($matches[1], array_keys($data)) === [];
      }
      
  3. Recipient Limits:

    • Bulk operations may hit database query limits. Use chunking for large recipient lists.
      $recipients = $entityManager->getRepository(User::class)->findAll();
      $chunkSize = 100;
      foreach (array_chunk($recipients, $chunkSize) as $chunk) {
          $communication->setRecipients($chunk);
          $entityManager->flush();
      }
      
  4. Template Caching:

    • Templates are not cached by default. For performance, implement a cache layer:
      $cacheKey = 'template_' . $template->getId();
      $content = $cache->get($cacheKey);
      if (!$content) {
          $content = $template->getContent();
          $cache->set($cacheKey, $content, 3600); // Cache for 1 hour
      }
      
  5. Transaction Management:

    • Large batch operations may require manual transaction management to avoid timeouts.
      $entityManager->beginTransaction();
      try {
          foreach ($users as $user) {
              $this->sendMessage($user);
              if ($i % 20 === 0) {
                  $entityManager->flush();
                  $entityManager->clear();
              }
          }
          $entityManager->commit();
      } catch (\Exception $e) {
          $entityManager->rollBack();
          throw $e;
      }
      

Debugging Tips

  1. Query Logging: Enable Doctrine query logging to debug MessageQueryBuilder issues:

    $entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    
  2. Event Debugging: Use OroPlatform’s event system to log communication steps:

    public function onCommunicationSent(CommunicationSentEvent $event)
    {
        \Log::debug('Communication sent', [
            'id' => $event->getCommunication()->getId(),
            'channel' => $event->getCommunication()->getChannel()->getType(),
        ]);
    }
    
  3. Template Rendering: Test template rendering in isolation:

    $data = ['user' => 'John Doe', 'orderId' => 12345];
    $rendered = $this->renderTemplate($template->getContent(), $data);
    // $rendered should output: "Your order 12345 is confirmed, John Doe!"
    

Extension Points

  1. Custom Channels: Extend the Channel entity to support new communication types (e.g., WhatsApp, Push Notifications).

    // src/Entity/CustomChannel.php
    class CustomChannel extends Channel
    {
        private $apiKey;
    
        // Add getters/setters and custom logic
    }
    
  2. Message Processors: Implement custom logic for message processing (e.g., validation, enrichment).

    // src/Processor/CustomMessageProcessor.php
    class CustomMessageProcessor implements MessageProcessorInterface
    {
        public function process(Message $message)
        {
            // Custom logic (e.g., add tracking, enrich data)
            $message->setMetadata(['processed_at' => new \DateTime()]);
        }
    }
    
  3. Criterion Builders: Create dynamic criterion builders for complex filtering.

    // src/Query/CustomCriterionBuilder.php
    class CustomCriterionBuilder
    {
        public function buildForActiveUsers(): Criterion
        {
            $criterion = new Criterion();
            $criterion->setField('user.isActive')
                      ->setOperator('=')
                      ->setValue(true);
            return $criterion;
        }
    }
    
  4. Event Subscribers: Hook into OroPlatform events to trigger communications automatically.

    // src/EventListener/CommunicationSubscriber.php
    class CommunicationSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'oro_integration.connect' => 'onIntegrationConnect',
            ];
        }
    
        public function onIntegrationConnect(IntegrationEvent $event)
        {
            // Trigger a welcome communication
        }
    }
    
  5. API Integration: Expose communication endpoints via OroPlatform’s API:

    # config/api/config.yml
    resources:
        communication
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle