Lesson 6: Asynchronous Handling
Asynchronous PHP Workers
Not having code for Lesson 6? git checkout lesson-6
Ecotone provides abstractions for asynchronous execution.

Asynchronous

We got new requirement: User should be able to place order for different products.
We will need to build Order aggregate.
Let's start by creating PlaceOrderCommand with ordered product Ids
1
namespace App\Domain\Order;
2
3
class PlaceOrderCommand
4
{
5
private int $orderId;
6
/**
7
* @var int[]
8
*/
9
private array $productIds;
10
11
/**
12
* @return int[]
13
*/
14
public function getProductIds(): array
15
{
16
return $this->productIds;
17
}
18
19
public function getOrderId() : int
20
{
21
return $this->orderId;
22
}
23
}
Copied!
We will need OrderedProduct value object, which will describe, cost and identifier of ordered product
1
namespace App\Domain\Order;
2
3
class OrderedProduct
4
{
5
private int $productId;
6
7
private int $cost;
8
9
public function __construct(int $productId, int $cost)
10
{
11
$this->productId = $productId;
12
$this->cost = $cost;
13
}
14
15
public function getCost(): int
16
{
17
return $this->cost;
18
}
19
}
Copied!
And our Order aggregate
1
namespace App\Domain\Order;
2
3
use App\Infrastructure\AddUserId\AddUserId;
4
use Ecotone\Messaging\Attribute\Asynchronous;
5
use Ecotone\Modelling\Attribute\Aggregate;
6
use Ecotone\Modelling\Attribute\AggregateIdentifier;
7
use Ecotone\Modelling\Attribute\CommandHandler;
8
use Ecotone\Modelling\Attribute\QueryHandler;
9
use Ecotone\Modelling\QueryBus;
10
11
#[Aggregate]
12
#[AddUserId]
13
class Order
14
{
15
#[AggregateIdentifier]
16
private int $orderId;
17
18
private int $buyerId;
19
20
/**
21
* @var OrderedProduct[]
22
*/
23
private array $orderedProducts;
24
25
private function __construct(int $orderId, int $buyerId, array $orderedProducts)
26
{
27
$this->orderId = $orderId;
28
$this->buyerId = $buyerId;
29
$this->orderedProducts = $orderedProducts;
30
}
31
32
#[CommandHandler("order.place")]
33
public static function placeOrder(PlaceOrderCommand $command, array $metadata, QueryBus $queryBus) : self
34
{
35
$orderedProducts = [];
36
foreach ($command->getProductIds() as $productId) {
37
$productCost = $queryBus->sendWithRouting("product.getCost", ["productId" => $productId]);
38
$orderedProducts[] = new OrderedProduct($productId, $productCost->getAmount());
39
}
40
41
return new self($command->getOrderId(), $metadata["userId"], $orderedProducts);
42
}
43
44
#[QueryHandler("order.getTotalPrice")]
45
public function getTotalPrice() : int
46
{
47
$totalPrice = 0;
48
foreach ($this->orderedProducts as $orderedProduct) {
49
$totalPrice += $orderedProduct->getCost();
50
}
51
52
return $totalPrice;
53
}
54
}
Copied!
placeOrder - Place order method make use of QueryBus to retrieve cost of each ordered product. You could find out, that we are not using application/json for product.getCost query, ecotone/jms-converter can handle array transformation, so we do not need to use json.
You could inject service into placeOrder that will hide QueryBus implementation from the domain, or you may get this data from data store directly. We do not want to complicate the solution now, so we will use QueryBus directly.
We do not need to change or add new Repository, as our exiting one can handle any new aggregate arriving in our system.
Let's change our testing class and run it!
1
class EcotoneQuickstart
2
{
3
private CommandBus $commandBus;
4
private QueryBus $queryBus;
5
6
public function __construct(CommandBus $commandBus, QueryBus $queryBus)
7
{
8
$this->commandBus = $commandBus;
9
$this->queryBus = $queryBus;
10
}
11
12
public function run() : void
13
{
14
$this->commandBus->sendWithRouting(
15
"product.register",
16
["productId" => 1, "cost" => 100]
17
);
18
$this->commandBus->sendWithRouting(
19
"product.register",
20
["productId" => 2, "cost" => 300]
21
);
22
23
$orderId = 100;
24
$this->commandBus->sendWithRouting(
25
"order.place",
26
["orderId" => $orderId, "productIds" => [1,2]]
27
);
28
29
echo $this->queryBus->convertAndSend("order.getTotalPrice", MediaType::APPLICATION_X_PHP_ARRAY, ["orderId" => $orderId]);
30
}
31
}
Copied!
1
bin/console ecotone:quickstart
2
Running example...
3
Start transaction
4
Product with id 1 was registered!
5
Commit transaction
6
Start transaction
7
Product with id 2 was registered!
8
Commit transaction
9
Start transaction
10
Commit transaction
11
400
12
Good job, scenario ran with success!
Copied!
We want to be sure, that we do not lose any order, so we will register our order.place Command Handler to run asynchronously using RabbitMQ now. Let's start by adding extension to Ecotone, that can handle RabbitMQ:
1
composer require ecotone/amqp
Copied!
We also need to add our ConnectionFactory to our Dependency Container.
Symfony - Local
Symfony - Docker
Laravel - Local
Laravel - Docker
Lite - Local
Lite - Docker
1
# Add AmqpConnectionFactory in config/services.yaml
2
3
services:
4
_defaults:
5
autowire: true
6
autoconfigure: true
7
App\:
8
resource: '../src/*'
9
exclude: '../src/{Kernel.php}'
10
Bootstrap\:
11
resource: '../bootstrap/*'
12
exclude: '../bootstrap/{Kernel.php}'
13
14
# You need to have RabbitMQ instance running on your localhost, or change DSN
15
Enqueue\AmqpExt\AmqpConnectionFactory:
16
class: Enqueue\AmqpExt\AmqpConnectionFactory
17
arguments:
18
- "amqp+lib://guest:[email protected]:5672//"
Copied!
1
# Add AmqpConnectionFactory in config/services.yaml
2
3
services:
4
_defaults:
5
autowire: true
6
autoconfigure: true
7
App\:
8
resource: '../src/*'
9
exclude: '../src/{Kernel.php}'
10
Bootstrap\:
11
resource: '../bootstrap/*'
12
exclude: '../bootstrap/{Kernel.php}'
13
14
# docker-compose.yml has RabbitMQ instance defined. It will be working without
15
# addtional configuration
16
Enqueue\AmqpExt\AmqpConnectionFactory:
17
class: Enqueue\AmqpExt\AmqpConnectionFactory
18
arguments:
19
- "amqp+lib://guest:[email protected]:5672//"
Copied!
1
# Add AmqpConnectionFactory in bootstrap/QuickStartProvider.php
2
3
namespace Bootstrap;
4
5
use Illuminate\Support\ServiceProvider;
6
use Enqueue\AmqpExt\AmqpConnectionFactory;
7
8
class QuickStartProvider extends ServiceProvider
9
{
10
public function register()
11
{
12
$this->app->singleton(AmqpConnectionFactory::class, function () {
13
return new AmqpConnectionFactory("amqp+lib://guest:[email protected]:5672//");
14
});
15
}
16
(...)
Copied!
1
# Add AmqpConnectionFactory in bootstrap/QuickStartProvider.php
2
3
namespace Bootstrap;
4
5
use Illuminate\Support\ServiceProvider;
6
use Enqueue\AmqpExt\AmqpConnectionFactory;
7
8
class QuickStartProvider extends ServiceProvider
9
{
10
public function register()
11
{
12
$this->app->singleton(AmqpConnectionFactory::class, function () {
13
return new AmqpConnectionFactory("amqp+lib://guest:[email protected]:5672//");
14
});
15
}
16
(...)
Copied!
1
# Add AmqpConnectionFactory in bin/console.php
2
3
// add additional service in container
4
public function __construct()
5
{
6
$this->container = new Container();
7
$this->container->set(Enqueue\AmqpExt\AmqpConnectionFactory::class, new Enqueue\AmqpExt\AmqpConnectionFactory("amqp+lib://guest:[email protected]:5672//"));
8
}
9
10
Copied!
1
# Add AmqpConnectionFactory in bin/console.php
2
3
// add additional service in container
4
public function __construct()
5
{
6
$this->container = new Container();
7
$this->container->set(Enqueue\AmqpExt\AmqpConnectionFactory::class, new Enqueue\AmqpExt\AmqpConnectionFactory("amqp+lib://guest:[email protected]:5672//"));
8
}
Copied!
We register our AmqpConnectionFactory under the class name Enqueue\AmqpLib\AmqpConnectionFactory. This will help Ecotone resolve it automatically, without any additional configuration.
Let's add our first AMQP Backed Channel (RabbitMQ Channel), in order to do it, we need to create our first Application Context. Application Context is a non-constructor class, responsible for extending Ecotone with extra configurations, that will help the framework act in a specific way. In here we want to tell Ecotone about AMQP Channel with specific name. Let's create new class App\Infrastructure\MessagingConfiguration.
1
namespace App\Infrastructure;
2
3
class MessagingConfiguration
4
{
5
#[ServiceContext]
6
public function orderChannel()
7
{
8
return [
9
AmqpBackedMessageChannelBuilder::create("orders")
10
];
11
}
12
}
Copied!
ServiceContext - Tell that this method returns configuration. It can return array of objects or a single object.
Now we need to tell our order.place Command Handler, that it should run asynchronously using our neworders channel.
1
use Ecotone\Messaging\Annotation\Asynchronous;
2
3
(...)
4
5
#[Asynchronous("orders")]
6
#[CommandHandler("order.place", endpointId: "place_order_endpoint")]
7
public static function placeOrder(PlaceOrderCommand $command, array $metadata, QueryBus $queryBus) : self
8
{
9
$orderedProducts = [];
10
foreach ($command->getProductIds() as $productId) {
11
$productCost = $queryBus->sendWithRouting("product.getCost", ["productId" => $productId]);
12
$orderedProducts[] = new OrderedProduct($productId, $productCost->getAmount());
13
}
14
15
return new self($command->getOrderId(), $metadata["userId"], $orderedProducts);
16
}
Copied!
We do it by adding Asynchronous annotation with channelName used for asynchronous endpoint. Endpoints using Asynchronous are required to have endpointId defined, the name can be anything as long as it's not the same as routing key (order.place).
1
#[CommandHandler("order.place", endpointId: "place_order_endpoint")]
Copied!
You may mark Event Handler as asynchronous the same way.
Let's run our command which will tell us what asynchronous endpoints we have defined in our system: ecotone:list
1
bin/console ecotone:list
2
+--------------------+
3
| Endpoint Names |
4
+--------------------+
5
| orders |
6
+--------------------+
Copied!
We have new asynchronous endpoint available orders. Name comes from the message channel name. You may wonder why it is not place_order_endpoint, it's because via single asynchronous channel we can handle multiple endpoints, if needed. This is further explained in asynchronous section.
Let's change orderId in our testing command, so we can place new order.
1
public function run() : void
2
{
3
$this->commandBus->sendWithRouting(
4
"product.register",
5
["productId" => 1, "cost" => 100]
6
);
7
$this->commandBus->sendWithRouting(
8
"product.register",
9
["productId" => 2, "cost" => 300]
10
);
11
12
$orderId = 990;
13
$this->commandBus->sendWithRouting(
14
"order.place",
15
["orderId" => $orderId, "productIds" => [1,2]]
16
);
17
18
echo $this->queryBus->sendWithRouting("order.getTotalPrice", ["orderId" => $orderId]);
19
}
Copied!
After running our testing command bin/console ecotone:quickstartwe should get an exception:
1
AggregateNotFoundException:
2
3
Aggregate App\Domain\Order\Order:getTotalPrice was not found for indentifie
4
rs {"orderId":990}
Copied!
That's fine, we have registered order.place Command Handler to run asynchronously, so we need to run our asynchronous endpoint in order to handle Command Message. If you did not received and exception, it's probably because orderId was not changed and we already registered such order. Let's run our asynchronous endpoint
1
bin/console ecotone:run orders -vvv
2
[info] {"orderId":990,"productIds":[1,2]}
Copied!
Like we can see, it ran our Command Handler and placed the order. We can change our testing command to run only Query Handlerand check, if the order really exists now.
1
class EcotoneQuickstart
2
{
3
private CommandBus $commandBus;
4
private QueryBus $queryBus;
5
6
public function __construct(CommandBus $commandBus, QueryBus $queryBus)
7
{
8
$this->commandBus = $commandBus;
9
$this->queryBus = $queryBus;
10
}
11
12
public function run() : void
13
{
14
$orderId = 990;
15
16
echo $this->queryBus->sendWithRouting("order.getTotalPrice", ["orderId" => $orderId]);
17
}
18
}
Copied!
1
bin/console ecotone:quickstart -vvv
2
Running example...
3
400
4
Good job, scenario ran with success!
Copied!
There is one thing we can change. As in asynchronous scenario we may not have access to the context of executor to enrich the message,, we can change our AddUserIdService Interceptor to perform the action before sending it to asynchronous channel. This Interceptor is registered as Before Interceptor which is before execution of our Command Handler, but what we want to achieve is, to call this interceptor before message will be send to the asynchronous channel. For this there is Presend Interceptor available. Change Before annotation to Presend annotation and we are done.
1
namespace App\Infrastructure\AddUserId;
2
3
class AddUserIdService
4
{
5
#[Presend(0, AddUserId::class, true)]
6
public function add() : array
7
{
8
return ["userId" => 1];
9
}
10
}
Copied!
Ecotone will do it best to handle serialization and deserialization of your headers.
Now if non-administrator will try to execute this, exception will be thrown, before the Message will be put to the asynchronous channel. Thanks to Presend interceptor, we can validate messages, before they will go asynchronous, to prevent sending incorrect messages.
The final code is available as lesson-7: git checkout lesson-7
We made it through, Congratulations! We have successfully registered asynchronous Command Handler and safely placed the order. We have finished last lesson. You may now apply the knowledge in real project or check more advanced usages starting here Modelling Overview.
Last modified 9mo ago
Export as PDF
Copy link
Contents
Asynchronous