search
HomeBackend DevelopmentPHP TutorialUnderstanding the Domain and Building the Team: The Foundations of Change (II)

Embarking on a complex project necessitates comprehensive context gathering while simultaneously approaching domain knowledge from a fresh perspective, leveraging domain expert insights. This approach aligns the technical team with business objectives and establishes a foundational roadmap for informed decision-making throughout the product lifecycle.

Initial knowledge-gathering sessions with the previous team and current application users proved unproductive. We briefly considered proceeding independently, despite the inherent risks.

EventStorming: Unveiling the Domain

As tech lead, I championed a domain-driven approach from the outset, given the project's complexity and the team's need for ownership. This centered the domain, fostering a shared understanding (ubiquitous language) that streamlined communication and facilitated mapping the application's current state.

We initiated EventStorming sessions using a Miro template, providing structure and a legend for effective focus. Prior familiarity with EventStorming concepts, either through pre-session preparation or initial explanations, is highly beneficial.

Understanding the Domain and Building the Team: The Foundations of Change (II)

Our structured EventStorming process comprised:

  1. Exploring Domain Events (Big Picture): Identifying, chronologically ordering, and validating key system events with domain experts, highlighting gaps and dependencies.
  2. Refinement and Analysis: Adding explanatory notes, documenting questions, deeply analyzing each event, and pinpointing critical decision points.
  3. Domain Modeling: Identifying aggregates and boundaries, defining actors and roles, establishing triggering commands, documenting policies and business rules, and identifying internal/external event triggers.
  4. Documentation and Validation: Organizing and cleaning collected information, establishing clear relationships, validating the model with stakeholders, and creating reference documentation.

EventStorming provided not only domain understanding but also a foundation for applying Domain-Driven Design (DDD) principles strategically and tactically.

Strategic Domain-Driven Design

A crucial initial step involved strategically structuring the domain. The system's complexity and the need for technical/business alignment led to adopting DDD principles. Context Mapping proved invaluable, even within our monolith awaiting refactoring. We identified Bounded Contexts, operating within a single technical context with a shared kernel. This analysis, while not deeply explored, guided the project toward a domain-oriented architecture, improving both technical development and cross-team collaboration.

Defining Boundaries (Bounded Contexts)

Identifying Bounded Contexts clarified inter-system and external system relationships, simplifying complexity and establishing a foundation for future modularization. These initial decisions will guide the monolith's decomposition into manageable components aligned with defined contexts. This also facilitated prioritization and identification of areas for simplification, decoupling, or elimination. We focused on implementing Anti-Corruption Layers (ACL) for external system interaction, preserving system integrity.

Five key contexts were identified:

  • Order Assignment
  • Label Generation
  • Order Preparation
  • E-commerce Integration
  • Bulk Order Preparation

These decisions fostered sustainable architecture and aligned development with business needs.

Understanding the Domain and Building the Team: The Foundations of Change (II)

Ubiquitous Language

Establishing a robust ubiquitous language proved vital. The benefits of a shared language, created through collaboration between domain experts and developers, far outweigh translation efforts or misinterpretations. This living resource connected the technical team with domain experts, improving communication, reducing misunderstandings, and ensuring accurate domain representation in the code. This fostered efficient, business-aligned technical solutions.

Tactical Domain-Driven Design

Following the strategic framework, we implemented tactical DDD principles to structure the code, reflecting domain reality and ensuring long-term sustainability.

Entities and Value Objects

Understanding the distinction between Entities and Value Objects is crucial.

Entities

Entities possess a unique, persistent identity, even with attribute changes. Examples include:

  • Order
  • Product
  • Carrier
  • Shop
  • Customer

Value Objects

Value Objects lack individual identity; their value defines them. Identical attributes signify equivalence. They are immutable and ideal for encapsulating concepts appearing across the domain. Examples include:

  • ProductReference
  • ProductEan13
  • OrderReference
  • Price
  • Weight
  • ShippingNumber

This approach created more understandable and modular code with clearly defined responsibilities.

Example Value Object:

<?php
readonly class ProductEan13
{
    public string $value;

    public function __construct(string $value)
    {
        $pattern = '/^\d{13}$/';
        if (!preg_match($pattern, $value)) {
            throw new \Exception('Invalid product Ean13');
        }
        $this->value = $value;
    }
}

Services

Services are categorized by purpose and implemented patterns.

Domain Services

Domain Services encapsulate business logic not fitting into entities or values, operating strictly within domain rules without infrastructure dependencies.

<?php
readonly class ProductEan13
{
    public string $value;

    public function __construct(string $value)
    {
        $pattern = '/^\d{13}$/';
        if (!preg_match($pattern, $value)) {
            throw new \Exception('Invalid product Ean13');
        }
        $this->value = $value;
    }
}
Application Services

Application Services coordinate domain operations with external interactions, centralizing complex operations and separating domain and infrastructure. These include Use Cases, Command Handlers, and Event Handlers.

Understanding the Domain and Building the Team: The Foundations of Change (II)

Infrastructure Services

Infrastructure Services handle external component interactions (databases, file systems, etc.), acting as adapters to maintain domain agnosticism.

<?php
class CheapestCarrierGetter
{
    public function get(
        DeliveryOptionCarrierCollection $deliveryOptionCarriers,
        Weight $orderWeight,
        Country $country,
        PostalCode $postalCode,
        bool $isCashOnDelivery = false,
    ): Carrier {
        // Logic to get the cheapest carrier
    }
}
Service Classification

Services are classified by function and associated design patterns: Transformers, Builders, Factories, Presenters, Notifiers, Validators, and Clients.

This initial domain modeling, though incomplete and iterative, fostered team participation and commitment. Further refinement and restructuring were anticipated.

Recommended DDD resources:

  • "Domain-Driven Design: Tackling Complexity in the Heart of Software" by Eric Evans
  • "Implementing Domain-Driven Design" by Vaughn Vernon
  • "Domain-Driven Design in PHP" by Carlos Buenosvinos, Christian Soronellas & Keyvan Akbary

Building the Team: Tuckman's Stages

DDD adoption paralleled team formation, following Tuckman's stages (Forming, Storming, Norming, Performing).

Forming

Initial team members reviewed the project, documented operations, and established technical and organizational foundations (processes, standards, tools).

Storming

Minor disagreements led to defining working styles, communication methods, and decision-making processes.

Norming

Team agreements, coding standards, development processes, WIP limits, deployment rules, technical debt management, and ADRs were established.

Performing

The established framework enabled efficient product development, prioritizing valuable initiatives, and fostering a culture of continuous improvement.

Documentation: The Diátaxis Model

Documentation was managed using GitLab Pages and Jekyll with the Just the Docs theme, following the Diátaxis model: Tutorials, Guides, Explanations, and References. Automating documentation using Event Catalog and AsyncAPI was planned but not fully implemented.

The above is the detailed content of Understanding the Domain and Building the Team: The Foundations of Change (II). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.