description |
---|
Running the code asynchronously |
{% embed url="https://github.com/ecotoneframework/quickstart-examples/tree/main/Asynchronous" %}
{% embed url="https://github.com/ecotoneframework/quickstart-examples/tree/main/RefactorToReactiveSystem" %} Step by step refactor from synchronous code to full resilient asynchronous code {% endembed %}
Read more about Asynchronous in PHP and Ecotone
Building Reactive Message-Driven Systems in PHP
Let's create Event
Order was placed.
class OrderWasPlaced
{
private string $orderId;
private string $productName;
public function __construct(string $orderId, string $productName)
{
$this->orderId = $orderId;
$this->productName = $productName;
}
public function getOrderId(): string
{
return $this->orderId;
}
public function getProductName(): string
{
return $this->productName;
}
}
And Event Handler that will be listening to the OrderWasPlaced
.
class NotificationService
{
const ASYNCHRONOUS_MESSAGES = "asynchronous_messages";
#[Asynchronous("asynchronous_messages")]
#[EventHandler(endpointId:"notifyAboutNeworder")]
public function notifyAboutNewOrder(OrderWasPlaced $event) : void
{
echo "Handling asynchronously: " . $event->getProductName() . "\n";
}
}
Let's Ecotone
that we want to run this Event Handler Asynchronously using RabbitMQ
class Configuration
{
#[ServiceContext]
public function enableRabbitMQ()
{
return AmqpBackedMessageChannelBuilder::create(NotificationService::ASYNCHRONOUS_MESSAGES);
}
}
$eventBus->publish(new OrderWasPlaced(1, "Milk"));
# Running asynchronous consumer
$messagingSystem->run("asynchronous_messages");