# Asynchronous PHP

Make any handler async with a single attribute — retries, error handling, and dead letter included automatically.

## Demo

{% 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 Blog Post

[Read more about Asynchronous in PHP and Ecotone](https://blog.ecotone.tech/asynchronous-php/)

[Building Reactive Message-Driven Systems in PHP](https://blog.ecotone.tech/building-reactive-message-driven-systems-in-php/)

## Code Example

Let's create `Event` *Order was placed*.

```php
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`.

```php
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](https://www.rabbitmq.com/)

```php
class Configuration
{
    #[ServiceContext]
    public function enableRabbitMQ()
    {
        return AmqpBackedMessageChannelBuilder::create(NotificationService::ASYNCHRONOUS_MESSAGES);
    }
}
```

## Running The Example

```php
$eventBus->publish(new OrderWasPlaced(1, "Milk"));

# Running asynchronous consumer
$messagingSystem->run("asynchronous_messages");
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ecotone.tech/quick-start-php-ddd-cqrs-event-sourcing/asynchronous-php.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
