<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Razvan Dubau on Medium]]></title>
        <description><![CDATA[Stories by Razvan Dubau on Medium]]></description>
        <link>https://medium.com/@razvandubau?source=rss-902d966cb056------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M8AxK6QjPojFkez0i1JJCg.jpeg</url>
            <title>Stories by Razvan Dubau on Medium</title>
            <link>https://medium.com/@razvandubau?source=rss-902d966cb056------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:26:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@razvandubau/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OpenAPI as the Single Source of Truth]]></title>
            <link>https://medium.com/@razvandubau/openapi-as-the-single-source-of-truth-fe5f2185b430?source=rss-902d966cb056------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5f2185b430</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Razvan Dubau]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 06:39:59 GMT</pubDate>
            <atom:updated>2026-06-03T13:24:15.074Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Specs and Code Generators Transform Product Delivery</h4><p><strong><em>APIs are everywhere — and yet, building and integrating them is still much harder than it should be.</em></strong></p><p>Ask any team that works across backend, frontend, and mobile, and you’ll hear the same stories:</p><ul><li>❌ the backend changes a field name and the frontend breaks</li><li>❌ integration takes longer than implementation</li><li>❌ documentation is outdated from the moment it’s written</li><li>❌ everybody has their own copy of the “truth” in Confluence, Postman collections, Slack messages, and Excel files</li></ul><p>Most of these problems don’t come from technology. They come from <strong>misalignment</strong>.</p><p>This is where <strong>OpenAPI</strong> becomes much more than a documentation format. When used correctly, it becomes the <strong>contract</strong> that sits in the center of product development — from design to implementation, testing, validation, and versioning.</p><p>In this article, we’ll dive into how OpenAPI specs combined with generators change the way teams work, why the business benefits from it, and which technical capabilities it unlocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMVW0ek6vB4bM7PM-eZC9Q.png" /><figcaption>Code first, documentation after &lt;-&gt; Documentation first, code after (AI / Generated clients)</figcaption></figure><h3>Documentation vs. product contract</h3><p>OpenAPI is a machine-readable way to describe:</p><ul><li>endpoints</li><li>requests and responses</li><li>authentication</li><li>field types</li><li>constraints and validation rules</li><li>error formats</li></ul><p>The obvious thought here is that most teams see it as <strong>documentation. </strong>Still<strong>, </strong>if we shift a bit our perspective we can find that the OpenApi specs starts to be a real power when you think of it it as a <strong>contract</strong>.</p><p>Instead of backend developers implementing something and writing docs later, you <strong>flip</strong> the <strong>process</strong>:</p><ol><li>design the API spec</li><li>agree on it across teams (and sometimes with business)</li><li>commit it to Git</li><li>generate everything else from it</li></ol><p>Suddenly, the spec is the <strong>single source of truth </strong>for: frontend, backend, mobile, QA, product. All of them look at the <strong>same definition instead of guessing</strong>.</p><p>For business stakeholders, this means something very tangible:</p><blockquote><em>Fewer surprises, fewer misunderstandings, and faster delivery because teams stop arguing about </em>what<em> the API should look like and focus on </em>building<em>.</em></blockquote><p>Having a single source of truth is the necessary foundation, but it is also the catalyst for the next leap in productivity: <strong>AI-Powered Velocity</strong>.</p><p>By leveraging your OpenAPI spec as the context for AI, you can generate boilerplate code, comprehensive test suites, and complex integration logic in seconds rather than hours. This transforms the spec from a static reference into a living, automated blueprint that accelerates the entire development lifecycle.</p><h3>Generators for every language: stop hand-writing clients and models</h3><p>Once you have an OpenAPI spec, you can feed it into generators. There are many tools available (OpenAPI Generator, Swagger Codegen, Redocly, etc.), but the exact tool is less important than the approach.</p><p>From one spec file, you can automatically generate:</p><ul><li><strong>clients</strong> for: TypeScript / JavaScript, PHP, Java, C#, Go, etc.</li><li><strong>models and DTOs</strong></li><li><strong>server stubs</strong></li><li><strong>API documentation websites</strong></li><li><strong>mock servers for testing</strong></li></ul><p>Why this <strong>matters for developers</strong>:</p><ul><li>no more manually writing request code ✅</li><li>no more mismatched field names between BE and FE ✅</li><li>compile-time errors instead of runtime surprises (strict types) ✅</li><li>eliminates repetitive boilerplate ✅</li></ul><p>Why this <strong>matters for business</strong>:</p><ul><li>developers spend time on real features, not copy-pasting JSON structures</li><li>integration time between teams drops significantly</li><li>onboarding new developers becomes easier</li></ul><p>One spec → automatic clients across platforms → <strong>consistent APIs everywhere</strong>.</p><h3>Versioning becomes clear and predictable (Git tags &amp; private packages)</h3><p>If the OpenAPI spec is the contract, then <strong>versioning the contract</strong> becomes critical.</p><p>A simple and effective workflow looks like this:</p><ol><li>the OpenAPI spec lives in its own Git repository</li><li>changes are reviewed just like normal code</li><li>each release is tagged (for example, v1.4.2)</li><li>generators run in CI/CD pipelines</li><li>generated clients are published as <strong>private composer or npm packages</strong></li><li>backend and frontend depend on the same version number</li></ol><p>This has powerful consequences.</p><p>Technical teams get:</p><ul><li><strong>traceability (“frontend X uses API contract Y”)</strong></li><li>predictable breaking changes via semantic versioning</li><li>easy rollback if something fails</li></ul><p>Business gets:</p><ul><li>risk management around API changes</li><li>easier coordination between multiple teams</li><li>fewer integration failures in production</li></ul><p>Instead of “someone changed something and we don’t know what broke”, you get:</p><blockquote><em>“We upgraded from API contract 1.3 to 1.4 and here’s exactly what changed.”</em></blockquote><h3>Automatic backend input validation based on the spec</h3><p>This is one of the most underrated benefits.</p><p>The OpenAPI spec already knows:</p><ul><li>which fields are required</li><li>minimum/maximum values</li><li>string patterns (email, UUID, etc.)</li><li>enum values</li><li>nested structures and types</li></ul><p>Instead of rewriting those rules in backend code, you can:</p><ul><li>generate validation middleware</li><li>or connect runtime validators to the spec directly</li></ul><p>Then the backend automatically rejects invalid requests <strong>before</strong> your business logic runs.</p><p><strong>Developer benefits</strong>:</p><ul><li>less repetitive validation code</li><li>fewer edge case bugs</li><li>easier refactoring because validation lives in one place</li></ul><p><strong>Business benefits</strong>:</p><ul><li>increased security (bad input rejected early)</li><li>reduced time spent debugging integration issues</li><li>more reliable public APIs</li></ul><p>The spec stops being passive documentation and becomes part of the runtime behavior.</p><h3>Contract testing — the next logical step</h3><p>Even if you’ve never done contract testing, it’s worth understanding the idea.</p><p>Today many teams test like this:</p><ul><li>backend writes tests for backend</li><li>frontend tests frontend</li><li>integration issues appear only when systems talk to each other</li></ul><p>Contract testing shifts trust to the spec.</p><p>The workflow becomes:</p><ul><li>backend implementation must satisfy the OpenAPI contract</li><li>clients must satisfy how they consume the contract</li><li>mock servers can be generated automatically from the spec</li><li>consumer teams can start working before backend even exists</li></ul><p>This unlocks <strong>true parallel development</strong>.</p><p>Frontend teams can build UI logic using generated mock clients while backend teams are still implementing real endpoints. As long as everyone respects the contract, integration just works.</p><p>Business benefit:</p><blockquote><em>Features can be developed in parallel instead of waiting on other teams.</em></blockquote><h3>How this changes daily collaboration across teams</h3><p>The biggest impact isn’t technical, it’s organizational.</p><p>When the API spec becomes central:</p><ul><li>backend doesn’t “own” the truth</li><li>documentation is never “forgotten”</li><li>discussions become concrete (“rename this field?” not “how does this work?”)</li><li>teams align earlier, not during integration week</li><li>work can be distributed and parallelized</li></ul><p>Instead of implementation happening first and alignment second, OpenAPI enables:</p><blockquote><em>Alignment first, implementation second.</em></blockquote><p>This means:</p><ul><li>fewer meetings</li><li>fewer last-minute changes</li><li>shorter development cycles</li><li>more confident releases</li></ul><h3>Are there downsides? Yes — and they’re worth acknowledging</h3><p>Like any strong approach, this isn’t free.</p><p>Some realities:</p><ul><li><strong>maintaining the spec requires discipline </strong>❗</li><li>generators sometimes produce verbose or “ugly” code (still, the code stays in the /vendor directory)</li><li>developers need to learn tooling</li><li>not all edge cases are perfectly covered</li><li><strong>poorly</strong> <strong>designed</strong> specs bake in bad design everywhere ❗</li></ul><p>But in most organizations, the alternatives are worse as they development can drift between documentation and implementation and never be aligned. Also the manually created clients are a constant point of failure. But probably the most important is that there are a lot of<strong> hidden contracts living in people’s heads.</strong></p><h3>Final thoughts: design the contract, then build the software</h3><p>OpenAPI is not just for API documentation pages or Swagger UI demos.</p><p>Used correctly, it becomes:</p><ul><li>the <strong>contract between teams</strong></li><li>the <strong>source of truth for implementations</strong></li><li>the <strong>generator of clients, validators, and tests</strong></li><li>the <strong>foundation for reliable versioning</strong></li></ul><p>If your organization builds or consumes multiple services, you don’t just get technical advantages — you get:</p><ul><li>faster delivery</li><li>fewer integration bugs</li><li>clearer ownership</li><li>better communication between business and engineering</li></ul><p>APIs are contracts. OpenAPI simply gives us a modern way to treat them as such.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5f2185b430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to define and enforce a code structure in layered architecture]]></title>
            <link>https://medium.com/@razvandubau/how-to-define-and-a-enforce-a-code-structure-in-layered-architecture-338afc28121d?source=rss-902d966cb056------2</link>
            <guid isPermaLink="false">https://medium.com/p/338afc28121d</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Razvan Dubau]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 11:14:31 GMT</pubDate>
            <atom:updated>2024-03-12T05:50:25.954Z</atom:updated>
            <content:encoded><![CDATA[<p>I think there is not an unknown fact that during the lifespan of a large project many developers come and leave the team. Some of them bring with them a very good contribution, some are just doing their job and some of them… well, you got it. If your company is at the point where the business has reached a mature state and the application behind it evolves everyday, a clear set of rules would help the development team to stay consistent during every possible transition that might happen.</p><p>To provide some context, <a href="https://medium.com/@razvandubau/modernizing-php-app-using-ddd-with-symfony-60a58ed562bf">this article</a> would help understand the topic better, but on short, we are talking about a furniture online store (PHP with Symfony) that wants to migrate their monolith to a more modern and flexible technology using DDD along with layered architecture.</p><p>Throughout my years of experience, I’ve observed that it’s very challenging to have all the developers adhere to the same set of rules and ensure that they all contribute to the codebase as <strong>efficient</strong> as possible.</p><p><strong>Why saying efficient here?</strong></p><p>If you have very strict code guidelines but don’t use the proper tools to enforce the rules, the company will end up losing a bigger part of their budget on rigorous code reviews and technical debt. The code review will never catch everything and if there are mistakes at the software architecture level in the early stages everything from there on will translate in more an more costs for the business. The costs will go into the technical debt.</p><p>Also poor design will increase the time needed for a future tasks to get done.</p><p>The short conclusion is that development will slow down gradually and so the code quality.</p><p>As a solution to this wide and abstract problem the team can use tools like phpstan (static code analyser), which checks for complexity and problems in the code mostly in the low level parts, like classes and functions. Other mandatory tool can be considered a code style fixer. I won’t get into details which one is better here, because I want to switch the focus to the architecture level and not on a single function or class.</p><p>In the layered architecture context the simplest and most common structure for the code is that you have 3 base layers: Application, Domain and Infrastructure.</p><p>On our furniture store we decided to go with 3 layers:</p><ul><li>Application</li><li>Domain</li><li>Infrastructure</li></ul><p>As a general rule what we want to achieve here, is a very modular and flexible code. By using DDD we certainly want to isolate the <strong>domain</strong> in a way or another and keep it there like a map of the real business.</p><p>The <strong>application layer</strong> is responsible for facilitating user interaction with the domain, serving as the intermediary between the user and the underlying business/domain logic.</p><p>The <strong>infrastructure</strong> has the role to ensure that the application and domain layers can do what they have to. For example: saving an order, grabbing data from a database or a third party API. We should think at this layer as a section of the software which is replaceable or changeable.</p><p>An example can be, consuming a third party API to grab delivery costs for each region, which at some point in time will change its public interface by renaming the route. The application and domain layer should not care about that! They should only know that there is a service somewhere that will provide that functionality. How the service is implemented and what it does behind the scenes is considered an implementation detail.</p><blockquote><strong>How can we do this?<br></strong>We can achieve it by <strong>making the application layer to be dependent on an interface</strong>. Then, the infrastructure layer will have the duty to provide a <strong>concrete implementation</strong> for that interface.</blockquote><p>What we should notice here is that the infrastructure service can always be changed and the application and domain will not be affected since they depend on the interface and not on the service itself.</p><p>The problems start to arise when developers start to use a class from infrastructure directly into the application layer. By doing it the application layer is now tight coupled with the infrastructure layer. To avoid this problem, we should inject the services only by the interface name and let the dependency injection resolve which concrete implementation should be chosen from the infrastructure layer.</p><p>Another example might be that one domain will use an object that belongs to another domain. Like Order will create a Delivery object. (cross domain dependency)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6hnJYkh7eGEOzemsn-TZw.png" /><figcaption>Example of a <strong>wrong</strong> coupling between layers</figcaption></figure><p>The fix for te cross domain dependency will be to remove the Delivery dependency and have the OrderCreated domain <a href="https://medium.com/@razvandubau/modernizing-php-app-using-ddd-with-symfony-60a58ed562bf#72c3">event dispatched to the network</a> and let the Delivery domain listen to it and do its job.</p><p>For the Application &lt;-&gt; Infrastructure coupling issue we can make the <strong>CreateOrderHandler</strong> to depend on <strong><em>PersistsOrderInterface </em></strong>instead of <strong>OrderRepository<em>. </em></strong>Dependency injection will decide which repository should be injected for this interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAwH_Gb8S5taXL1RbkYWWA.png" /><figcaption>Example of a <strong>good</strong> coupling between Application and Infrastructure layers</figcaption></figure><p>It is enough to break one of these rules once. If that happens, for sue it will happen again and again.</p><h3>Solution</h3><p>We can use <strong><em>deptrac </em></strong><em>(</em><em>qossmic/deptrac on github)</em>, a static code analyser, that helps to keep the layer or class interaction under control.</p><p><strong>How it works:<br></strong>You create a yaml config file specifying which layers can interact between them, <strong>set a pipeline on every merge request</strong> and you’re done!</p><p>In this way developers will be forced to understand the issue they are creating. Understanding it and with the power of habit their skills will improve. A win-win for both programmers and companies.</p><pre># deptrac.yml<br>imports:<br>  - deptrac.baseline.yaml<br>parameters:<br>  paths:<br>    - ./src<br>  layers:<br>    # Domain layers<br>    - name: OrderDomain<br>      collectors:<br>        - type: className<br>          regex: App\\Order\\Domain\\.*<br>    - name: DeliveryDomain<br>      collectors:<br>        - type: className<br>          regex: App\\Delivery\\Domain\\.*<br><br>    # Infrastructure layers<br>    - name: OrderInfrastructure<br>      collectors:<br>        - type: className<br>          regex: App\\Order\\Infrastructure\\.*<br>    - name: DeliveryInfrastructure<br>      collectors:<br>        - type: className<br>          regex: App\\Delivery\\Infrastructure\\.*<br><br>    # Application layers<br>    - name: OrderApplication<br>      collectors:<br>        - type: className<br>          regex: App\\Order\\Application\\.*<br>    - name: DeliveryApplication<br>      collectors:<br>        - type: className<br>          regex: App\\Delivery\\Application\\.*<br><br>    # Common collectors<br>    - name: CommonApplication<br>      collectors:<br>        - type: className<br>          regex: App\\Common\\Application\\.*<br>  ruleset:<br>    OrderInfrastructure:<br>      - OrderApplication<br>      - OrderDomain<br>    OrderApplication:<br>      - CommonApplication<br>      - OrderDomain<br><br>    DeliveryInfrastructure:<br>      - DeliveryApplication<br>      - DeliveryDomain<br>    DeliveryApplication:<br>      - CommonApplication<br>      - DeliveryDomain<br>  exclude_files:<br>    - &#39;#.*Tests.*#&#39;</pre><p>The above configuration will show the following report if we test the code from the screenshot containing the wrong coupling examples:</p><pre> ----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------- <br>  Reason      OrderApplication                                                                                                                                               <br> ----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------- <br>  Violation   App\Order\Application\CommandHandler\CreateOrderHandler must not depend on App\Order\Infrastructure\Doctrine\Repository\OrderRepository (OrderInfrastructure)  <br>              /Users/razvandubau/projects/furniture-demo/src/App/Order/Application/CommandHandler/CreateOrderHandler.php:18                                                  <br>  Violation   App\Order\Application\CommandHandler\CreateOrderHandler must not depend on App\Delivery\Domain\Delivery (DeliveryDomain)                                       <br>              /Users/razvandubau/projects/furniture-demo/src/App/Order/Application/CommandHandler/CreateOrderHandler.php:29                                                  <br>  Violation   App\Order\Application\CommandHandler\CreateOrderHandler must not depend on App\Delivery\Domain\Delivery (DeliveryDomain)                                       <br>              /Users/razvandubau/projects/furniture-demo/src/App/Order/Application/CommandHandler/CreateOrderHandler.php:6                                                   <br>  Violation   App\Order\Application\CommandHandler\CreateOrderHandler must not depend on App\Order\Infrastructure\Doctrine\Repository\OrderRepository (OrderInfrastructure)  <br>              /Users/razvandubau/projects/furniture-demo/src/App/Order/Application/CommandHandler/CreateOrderHandler.php:11                                                  <br> ----------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------<br><br>-------------------- ----- <br>  Report                    <br> -------------------- ----- <br>  Violations           4    <br>  Skipped violations   0    <br>  Uncovered            0    <br>  Allowed              18   <br>  Warnings             0    <br>  Errors               0    <br> -------------------- -----</pre><p>By removing the dependency on the <strong>Delivery</strong> class and also using <strong>PersistsOrderInterface</strong> the deptrac report will look like:</p><pre>-------------------- ----- <br>  Report                    <br> -------------------- ----- <br>  Violations           0    <br>  Skipped violations   0    <br>  Uncovered            0    <br>  Allowed              18   <br>  Warnings             0    <br>  Errors               0    <br> -------------------- -----</pre><p><strong>Conclusion</strong></p><p>Deptrac is a potent tool that limits the interactions between layers and helps the team to be consistent code wise, and keep the boundaries clean.</p><p>The tool itself is for PHP, but if you read until here and you’re working with a different language, don’t get discouraged as the concept stay the same. Most probably there are similar tools for other programming languages.</p><p><strong>Note: </strong>You can see in the deptrac.yml file that and in the code screenshot that both domains, Order and Delivery, are in the same codebase. That shouldn’t be a problem since the domains don’t depend on each other. They can easily be separated into independent micro-services by extracting the domain code (Application, Domain and Infrastructure) along with the common helpers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338afc28121d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modernizing PHP apps using DDD with Symfony]]></title>
            <link>https://medium.com/@razvandubau/modernizing-php-app-using-ddd-with-symfony-60a58ed562bf?source=rss-902d966cb056------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a58ed562bf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Razvan Dubau]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 17:38:16 GMT</pubDate>
            <atom:updated>2024-03-11T11:16:28.088Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of web development, constant evolution is not just desirable; it’s imperative. As technology progresses, so do the demands and expectations of users. Modernizing existing PHP applications to meet contemporary standards is a challenge many companies face.</p><p>In this article, we’ll explore how to revitalize a PHP application using Domain-Driven Design (DDD) principles with the Symfony framework. We’ll discuss the tools and methodologies required for this transformation. We will delve into the Symfony Messenger component and how we can abstract and easily switch the way the system processes an action.</p><p>To make use of all the mentioned above, we’ll have to first discuss the integration of DDD with a Layered architecture, specifically Command Query Responsibility Segregation (CQRS).</p><h4><strong>Architectural key concepts</strong></h4><p><strong>Domain-Driven Design</strong> (DDD) is a software development approach that emphasizes modeling software based on the business domain. One of the key architectural patterns within DDD is Layered Architecture, which promotes the separation of concepts and concerns and modularization. When combined with Command Query Responsibility Segregation (CQRS), DDD becomes a potent framework for modernizing PHP applications.</p><p><strong>Layered Architecture</strong>: In a layered architecture, the <strong>application is divided</strong> <strong>into distinct layers</strong>, each responsible for a specific set of functionalities. Common layers include <strong>application</strong> services, <strong>domain</strong>, and <strong>infrastructure</strong>. By separating concerns and enforcing boundaries between layers, developers can achieve greater flexibility, scalability, and maintainability.</p><p><strong>CQRS</strong>: Command Query Responsibility Segregation (CQRS) is a design pattern that advocates for the segregation of read and write operations within an application. By decoupling commands (write operations) from queries (read operations), CQRS enables optimization for specific use cases, improving performance and scalability. Implementing CQRS within a DDD context fosters a clear separation of concerns and aligns closely with the principles of domain modeling.</p><h4>Monolith with service based approach vs DDD with layered architecture</h4><p>We will analyze how both approaches function within the context of an online furniture store. Reflecting on the typical REST API controller -&gt; service examples prevalent in Symfony documentation and other frameworks over the past decade, it’s evident that when implementing an endpoint such as GET /api/orders, the conventional pattern involves a OrderController invoking an OrderService, which in turn interacts with the OrderRepository to retrieve the list from the database. Subsequently, the data is returned through the entire chain, often accompanied by a serialization process conducted within the controller. Thus far, this approach suffices for most simple APIs, albeit not the most optimal one.</p><p>When considering the creation of an order, which prompts us to think of an endpoint like POST /api/orders. Using the service-based approach like for the GET endpoint, we can easily reach <strong>very long execution times</strong>.</p><p><strong>Why?<br></strong>Imagine a scenario, but not limit to this, where creating an <strong>Order</strong> involves a series of actions/tasks across different domains. To understand this we can focus on 4 tasks for now:</p><ul><li>check and update the inventory</li><li>send email notification to the client</li><li>send SMS notification to the client</li><li>book a delivery slot for the created order</li></ul><p>Looking at this chain of actions that need to be taken we can easily asses that the creation of an order can take more than few seconds. If we use third party clients for email and sms notifications we might get some latency for those as well.</p><p>From a delivery standpoint, determining the optimal time slot and selecting a vehicle with sufficient capacity among a fleet of hundreds or thousand of cars requires substantial computational resources.</p><p>On the other had, the inventory update should be a easy task, part of the inventory domain, that has to be executed in the same thread with the creation of the order to make sure that the product is not out of stock due to concurent orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKlNpFB6jedT3ZvQHA7-VA.png" /><figcaption>Check the inventory, create the order, send email and sms, book a delivery slot</figcaption></figure><p><strong>How will all these tasks impact the UX? </strong><br>The user will have to wait for a long time looking at a loading spinner.</p><p><strong>How it will affect the servers?</strong><br>In general if we have executions that have to run for more than x seconds and consume a lot of RAM memory, the server will soon get into memory issues or timeout errors. Of course we can increase these settings, but do we want it? Of course not! That’s the first sign of a bad architectural design.</p><p><strong>What would be the next option in this case without using DDD?</strong> <br>Usually, what technical teams tend to do in these scenarios is to study a message queue system like rabbitMQ, AWS SQS, Kafka and others, in order to decouple the long execution tasks from the API endpoint and make the route respond faster so the user gets a better experience.</p><p>The team will then modify the OrderService to push a series of messages to a queue and process them asynchronously instead of directly calling the EmailService, SmsService and DeliveryService to do their tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vb4U3jw_V-2OauLEQ0cTvg.png" /><figcaption>Create order and start an async task for the email, sms and delivery tasks</figcaption></figure><p>This will work, but the code itself and the changes needed for the code architecture and structure tend to be quite big for a single action.</p><p><strong>(*) </strong>Also probably you noticed that the OrderController is not capable to respond with data about Delivery anymore, since the processing of the delivery happens now in a separate asynchronous task.</p><p>Because the business evolve, the team can get into the same problem again with a different set of connected actions between business domains. The solution will be to change another service to queue a message instead of direct service call again and again. This will enforce another rethink about how the queues and workers are built up.</p><p>All of the above steps cause <strong>a lot of unexpected work</strong> for the team and also <strong>unexpected costs</strong> for the business!</p><p><strong>What if we can design a system that is modular enough and can deal with synchronous or asynchronous messages from day one?</strong></p><p>As you can expect the solution for this problems is using DDD with Layered architecture along and <strong>Symfony Messenger.</strong></p><p>The use of messenger is quite simple. We will need a rabbitMQ container/instance to connect the messenger component with and very few configurations for it.</p><p>What we want to achieve is to be able to dispatch a Command sync or async based on a simple interface implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYEOjXFe9F_DUvh-9n9uLQ.png" /><figcaption>Create order, dispatch async email and sms task and dispatch domain event</figcaption></figure><p>We can see in the above schema that the OrderController creates a new Command object, which contains all the necessary order data. The CreateOrderCommand is then sent to the message bus (sf messenger), which decides if the job will be processed synchronously or asynchronously.</p><pre>namespace App\Order\Domain\Command;<br><br>final class CreateOrderCommand<br>{<br>  private array $articles;<br>  private float $amount;<br>}</pre><p>In this case, the CreateOrderCommand is dispatched as a synchronous task. First, the Order domain has to communicate with the Inventory domain to determine if the articles are still available. This communication should occur between domains synchronously. As a solution to this, we can make curl calls from the Order domain infrastructure layer.</p><p>Next, when the CreateOrderHandler finishes processing and saving the data, it has to dispatch two commands: <strong>SendEmailCommand</strong> and <strong>SendSmsCommand</strong>.</p><pre>namespace App\Order\Domain\Command\CreateOrder;<br><br>use App/MessageBus/ProcessAsynchronouslyInterface;<br><br>final class SendEmailCommand implements ProcessAsynchronouslyInterface <br>{<br>  private string $userFirstName;<br>  private string $userLastName;<br>  private string $email;<br>  ...<br>}</pre><pre>namespace App\Order\Domain\Command\CreateOrder;<br><br>use App/MessageBus/ProcessAsynchronouslyInterface;<br><br>final class SendSmsCommand implements ProcessAsynchronouslyInterface <br>{<br>  private string $userFirstName;<br>  private string $userLastName;<br>  private string $phoneNumber;<br>  ...<br>}</pre><p>Ultimately, the Order domain triggers a domain event, enabling any subscriber to perform actions based on this specific business event. In our scenario, we refer to the Delivery domain, which must listen to this event and dispatch various commands within its domain to facilitate the delivery process.</p><pre>namespace App\DomainEvents;<br><br>final class OrderEvents<br>{<br>  public const ORDER_CREATED = &#39;order_created&#39;;<br><br>  ...<br>}</pre><pre>namespace App\DomainEvents\Order;<br><br>use App/DomainEvents/OrderEvents;<br><br>final class OrderCreatedEvent implements DomainEventInterface<br>{<br>  public function __construct(public string $uuid)<br>  {<br>  }<br><br>  public function getEventName(): string<br>  {<br>    return OrderEvents::ORDER_CREATED;<br>  }<br>}</pre><pre>namespace App\Order\Application\CommandHandler;<br><br>class CreateOrderHandler<br>{<br>  public function __construct(private MessageBusInterface $messageBus)<br>  {}<br><br>  public function __invoke(CreateOrderCommand $command)<br>  {<br>    <br>    /* <br>      Check the inventory. We can do it by a curl or Symfony sub-request if <br>      the domains share the same Symfony instance.<br>    */<br><br>    $order = // Create and save the Order entity.<br><br>    $sendEmailCommand = new SendEmailCommand(/* Order details to be added here*/);<br>    $this-&gt;messageBus-&gt;dispatch(Envelope::wrap($sendEmailCommand));<br><br>    $sendSmsCommand = new SendSmsCommand(/* Order details to be added here*/);<br>    $this-&gt;messageBus-&gt;dispatch(Envelope::wrap($sendSmsCommand));<br><br>    // Dispatch the order created domain event<br>    $orderCreatedEvent = new OrderCreatedEvent($order-&gt;getUuid());<br>    $this-&gt;messageBus-&gt;dispatch(Envelope::wrap($orderCreatedEvent);<br>  }<br>}</pre><p>In conclusion, the same architectural pattern is employed for all Command/Handler pairs. One (CreateOrderCommand) is processed directly, while the other two are processed as entirely decoupled tasks (sending SMS and email). Additionally, a domain event is dispatched to all subscribers, with the Delivery domain subscribing to it via the fanout exchange named domain_events .</p><p><strong>How things are running synchronously or asynchronously, and how do we ensure they function accordingly?</strong><br>With the benefit of the messenger component, we can simply add an interface to the SendEmailCommand and SendSmsCommand and route that interface to an asynchronous transport, implicitly to RabbitMQ.</p><pre># config/packages/messenger.yaml<br>framework:<br>  messenger:<br>    buses:<br>      messenger.bus.default:<br>        default_middleware: false<br>        middleware:<br>          - id: &#39;add_bus_name_stamp_middleware&#39;<br>            arguments:<br>              - &#39;messenger.bus.default&#39;<br>          - &#39;dispatch_after_current_bus&#39;<br>          - &#39;failed_message_processing_middleware&#39;<br>          - &#39;send_message&#39;<br>          - &#39;handle_message&#39; # this will execute the task synchronously <br>      transports:<br>        async_tasks:<br>          dsn: &#39;%env(AMQP_URL)%&#39;<br>          options:<br>            exchange:<br>              name: app_async_tasks<br>              type: fanout<br>            queues:<br>              app_async_tasks: ~<br><br>        domain_events:<br>          dsn: &#39;%env(AMQP_URL)%&#39;<br>          options:<br>            exchange:<br>              name: domain_events<br>              type: fanout<br>            queues:<br>              domain_events: ~<br>      routing:<br>        App\MessageBus\ProcessAsynchronouslyInterface : async_tasks # this will force any ProcessAsynchronously command to be processed async<br>        App\MessageBus\DomainEventInterface : domain_events</pre><p>Commands that implement the ProcessAsynchronouslyInterface will be executed as asynchronous tasks, while events implementing the DomainEventInterface are processed asynchronously by multiple handlers across the domains. Each of these handlers or event-listeners will then create different commands and dispatch them internally as synchronous or asynchronous tasks.</p><p>By repeating this architectural pattern, we can achieve and execute anything that the domain requires in a highly decoupled and flexible manner.</p><p><strong>(*) </strong><em>Since the delivery is processed separately, our app is no longer capable of returning the delivery costs and time estimations together with the confirmation that the order was created. Here, we need to change our mindset and let go of the idea that an endpoint should handle and return everything.<br>Possible solutions in this case include either using websockets (where the delivery domain, upon completing its job, pushes a notification to the browser), or having the frontend app continuously fetch the data in a loop until the delivery domain has finished processing.</em></p><p><strong>Is this everything we need for migrating a legacy project to a modern architecture?</strong></p><p><strong>No!</strong> There will be a lot of challenges ahead, such as:</p><ul><li>Single database for all domains<br> — How does the Delivery Domain read data from the Order Domain?<br> — How does the Order Domain read from the Inventory Domain before creating an order?</li><li>Deliver the new app in parallel with the old one</li><li><a href="https://medium.com/@razvandubau/how-to-define-and-a-enforce-a-code-structure-in-layered-architecture-338afc28121d">Keep the code base clean and avoid overlapping infrastructure with the domain</a> (deptrac helps here)</li></ul><p>For all of these topics, we will discuss them in separate articles, so stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a58ed562bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>