PHP code example of azaharizaman / nexus-messaging
1. Go to this page and download the library: Download azaharizaman/nexus-messaging library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
azaharizaman / nexus-messaging example snippets
use Nexus\Messaging\Contracts\MessagingRepositoryInterface;
use Nexus\Messaging\ValueObjects\MessageRecord;
final class EloquentMessagingRepository implements MessagingRepositoryInterface
{
public function saveRecord(MessageRecord $record): void
{
DB::table('messages')->insert($record->toArray());
}
public function findById(string $id): ?MessageRecord
{
$data = DB::table('messages')->where('id', $id)->first();
// ... convert to MessageRecord VO
}
public function findByEntity(string $entityType, string $entityId, int $limit = 50, int $offset = 0): array
{
// ... query implementation
}
// ... other methods
}
use Nexus\Messaging\Contracts\MessagingConnectorInterface;
use Nexus\Messaging\ValueObjects\MessageRecord;
use Nexus\Messaging\Enums\DeliveryStatus;
final class TwilioWhatsAppConnector implements MessagingConnectorInterface
{
public function send(MessageRecord $draft): MessageRecord
{
// Call Twilio API
$response = $this->twilioClient->messages->create(
"whatsapp:{$draft->recipientPartyId}",
[
'from' => "whatsapp:{$this->twilioNumber}",
'body' => $draft->body
]
);
// Return updated record with delivery status
return $draft->withDeliveryStatus(
DeliveryStatus::Sent,
$response->sid
);
}
public function processInboundWebhook(array $payload): MessageRecord
{
// Parse Twilio webhook payload
return MessageRecord::createInbound(
id: $this->generateId(),
channel: Channel::WhatsApp,
subject: null,
body: $payload['Body'],
receivedAt: new \DateTimeImmutable($payload['DateCreated']),
senderPartyId: $this->parsePhoneNumber($payload['From']),
recipientPartyId: $this->parsePhoneNumber($payload['To']),
tenantId: $this->getCurrentTenantId(),
providerReferenceId: $payload['MessageSid']
);
}
public function getSupportedChannel(): string
{
return 'whatsapp';
}
public function isConfigured(): bool
{
return !empty($this->twilioAccountSid);
}
}
use Nexus\Messaging\Services\MessageManager;
use Nexus\Messaging\Enums\Channel;
$messageManager = new MessageManager(
repository: $messagingRepository,
connector: $twilioConnector,
logger: $logger
);
// Send WhatsApp message
$message = $messageManager->sendMessage(
id: 'msg-' . Str::ulid(),
channel: Channel::WhatsApp,
subject: null,
body: 'Hello! Your order has shipped.',
senderPartyId: 'company-support',
recipientPartyId: '+60123456789',
tenantId: 'tenant-001',
entityType: 'order',
entityId: 'order-12345'
);
echo "Message sent: {$message->deliveryStatus->label()}";
// Webhook endpoint (e.g., Laravel controller)
public function handleTwilioWebhook(Request $request)
{
$inboundMessage = $messageManager->processInboundWebhook(
$request->all()
);
// Message automatically saved to database
// Can trigger workflows, notifications, etc.
return response('OK', 200);
}
// Get all messages for a support case
$timeline = $messageManager->getConversationTimeline(
entityType: 'case',
entityId: 'case-789',
limit: 50
);
foreach ($timeline as $message) {
echo "{$message->sentAt->format('Y-m-d H:i')} - ";
echo "{$message->direction->label()} {$message->channel->label()}: ";
echo "{$message->body}\n";
}
$message = MessageRecord::createOutbound(
// ...
body: 'Your SSN is 123-45-6789',
containsPII: true // Flag for compliance
);
// Application layer implementation
public function saveRecord(MessageRecord $record): void
{
$encryptedBody = $record->containsPII
? $this->encryptor->encrypt($record->body)
: $record->body;
DB::table('messages')->insert([
// ... other fields
'body' => $encryptedBody,
'encrypted' => $record->containsPII,
]);
}
// Mark messages for archival
$archived = $message->withArchivalStatus(ArchivalStatus::PreArchived);
// Application layer batch job
$messagesToArchive = $repository->findByArchivalStatus(
ArchivalStatus::PreArchived
);
foreach ($messagesToArchive as $msg) {
$this->archiver->moveToArchive($msg);
}
$messageManager = new MessageManager(
repository: $repository,
connector: $connector,
rateLimiter: $redisRateLimiter // Optional
);
// Automatically enforced before sending
$message = $messageManager->sendMessage(/* ... */);
// Throws RateLimitExceededException if quota exceeded
// Fast query for UI timeline (limit 20, optimized indexes)
$latestMessages = $messageManager->getLatestMessages(
entityType: 'customer',
entityId: 'cust-123',
limit: 20
);
public function test_can_send_whatsapp_message(): void
{
$connector = new TwilioWhatsAppConnector(/* ... */);
$repository = new InMemoryMessageRepository();
$manager = new MessageManager($repository, $connector);
$message = $manager->sendMessage(
id: 'msg-001',
channel: Channel::WhatsApp,
subject: null,
body: 'Hello',
senderPartyId: 'party-1',
recipientPartyId: '+60123456789',
tenantId: 'tenant-1'
);
$this->assertTrue($message->isOutbound());
$this->assertSame(DeliveryStatus::Sent, $message->deliveryStatus);
}