git checkout lesson-3
JSON
or XML
.
At the level of application however we want to deal with it in PHP
format, as objects or arrays.Ecotone
does provide extension point in which we can integrate different Media Type converters. JSON
to our PHP
format. In order to do that, we will need to implement Converter
interface and mark it with MediaTypeConverter().
TypeDescriptor
- Describes type in PHP format. This can be class, scalar (int, string), array
etc. MediaType
- Describes Media type format. This can be application/json
, application/xml
etc. $source
- is the actual data to be converted. matches
method. Which tells us, if this converter can do conversion from one type to another.Ecotone
that in case source media type is JSON
and target media type is PHP
, then it should use this converter.
Now we need to implement the convert method now. We will do it with pretty naive solution, just to proof the concept. JMS Serializer
or Symfony Serializer
to make the conversion.fromArray
method to RegisterProductCommand
and GetProductPriceQuery.
PHP objects
instead of JSON
, right?
In order to start sending commands
and queries
in different format, we need to provide our handlers with routing key. So Command and Query buses
will know, where to route the message. JSON
format.convertAndSend.
It takes as first argument routing key
to which we want to send the message.
The second argument describes the format
of message we send.
Third is the data to send itself, in this case command formatted as JSON
.Ecotone
comes with integration with JMS Serializer and extending it with extra features.
Let's replace our own written Converter with JMS Serializer integration.
Let's download the Converter using Composer.
composer require ecotone/jms-converter
__construct
andfromArray
methods from RegisterProductCommand
GetProductPriceQuery
and the App\Domain\Product\JsonToPHPConverter
class completely, as we won't need it anymore.Ecotone JMS
reads properties and deserializes according to type hint or docblock if it is array. Product should be registered only with positive cost
We could put constraint in Product
, validating the Cost
amount. But this would assure us only in that place, that this constraint is met and we want to be sure, that the Cost
is correct, whenever we make use of it, so we can avoid potential future bugs.
To achieve that we will create Value Object named Cost
that will handle the validation, during the construction. Ecotone JMS
does provide extension points, so we can tell him, how to convert specific classes. App\Infrastructure\Converter\CostConverter.
We will put it in different namespace, to separate it from the domain.Converter()
, so Ecotone
can read parameter type and return type in order to know, how he can convert from scalar/array to specific class and vice versa.
Let's change our command and aggregate class, so it can use the Cost directly.$cost
class property will be automatically converted from integer
to Cost
after calling Command Bus
.