Asynchronous PHP
Running the code asynchronously

What is Asynchronous Processing and What Does It Give

To The Code!

Let's create Event Order was placed.
1
class OrderWasPlaced
2
{
3
private string $orderId;
4
private string $productName;
5
6
public function __construct(string $orderId, string $productName)
7
{
8
$this->orderId = $orderId;
9
$this->productName = $productName;
10
}
11
12
public function getOrderId(): string
13
{
14
return $this->orderId;
15
}
16
17
public function getProductName(): string
18
{
19
return $this->productName;
20
}
21
}
Copied!
And Event Handler that will be listening to the OrderWasPlaced.
1
class NotificationService
2
{
3
const ASYNCHRONOUS_MESSAGES = "asynchronous_messages";
4
5
#[Asynchronous("asynchronous_messages")]
6
#[EventHandler(endpointId:"notifyAboutNeworder")]
7
public function notifyAboutNewOrder(OrderWasPlaced $event) : void
8
{
9
echo "Handling asynchronously: " . $event->getProductName() . "\n";
10
}
11
}
Copied!
Let's Ecotone that we want to run this Event Handler Asynchronously using RabbitMQ
1
class Configuration
2
{
3
#[ServiceContext]
4
public function enableRabbitMQ()
5
{
6
return AmqpBackedMessageChannelBuilder::create(NotificationService::ASYNCHRONOUS_MESSAGES);
7
}
8
}
Copied!

Running The Example

1
$eventBus->publish(new OrderWasPlaced(1, "Milk"));
2
3
# Running asynchronous consumer
4
$messagingSystem->run("asynchronous_messages");
Copied!

Implementation Using Lite