digitalstate/platform-communication-bundle
## 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],
];
Database Migrations: Run migrations to create the required tables:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
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();
{{user}}) for dynamic content.
$template->setContent('Your order {{orderId}} is confirmed.');
Channel entity (e.g., email, sms).
$emailChannel = $entityManager->getRepository(Channel::class)->findOneBy(['type' => 'email']);
$template->setChannel($emailChannel);
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();
Communication entity.
$communication = new Communication();
$communication->setTemplate($template)
->setRecipients([$user1, $user2])
->setChannel($channel);
$entityManager->persist($communication);
$entityManager->flush();
Criterion to filter recipients dynamically.
$criterion = new Criterion();
$criterion->setField('user.age')
->setOperator('>')
->setValue(18);
$communication->addCriterion($criterion);
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);
oro_integration.connect).
// Example: Trigger a communication on user registration
public function onUserRegistered(UserRegisteredEvent $event)
{
$user = $event->getUser();
$this->sendWelcomeEmail($user);
}
# config/workflows/welcome_email.yml
steps:
- action: send_communication
args:
template: welcome_email
recipients: [@user]
Channel Configuration:
email, sms) are properly configured in the database. Missing channels will cause errors.php bin/console oro:platform:install:channels (if available) or manually insert records into the channel table.Placeholder Parsing:
{{missing}}) will not render gracefully. Always validate placeholders before sending.private function validatePlaceholders(string $content, array $data): bool
{
preg_match_all('/\{\{(\w+)\}\}/', $content, $matches);
return array_diff($matches[1], array_keys($data)) === [];
}
Recipient Limits:
$recipients = $entityManager->getRepository(User::class)->findAll();
$chunkSize = 100;
foreach (array_chunk($recipients, $chunkSize) as $chunk) {
$communication->setRecipients($chunk);
$entityManager->flush();
}
Template Caching:
$cacheKey = 'template_' . $template->getId();
$content = $cache->get($cacheKey);
if (!$content) {
$content = $template->getContent();
$cache->set($cacheKey, $content, 3600); // Cache for 1 hour
}
Transaction Management:
$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;
}
Query Logging:
Enable Doctrine query logging to debug MessageQueryBuilder issues:
$entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
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(),
]);
}
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!"
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
}
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()]);
}
}
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;
}
}
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
}
}
API Integration: Expose communication endpoints via OroPlatform’s API:
# config/api/config.yml
resources:
communication
How can I help you explore Laravel packages today?