Å·±¦ÓéÀÖ

Jump to ratings and reviews
Rate this book

Domain-Driven Design in PHP: A Highly Practical Guide

Rate this book
Domain-Driven Design (DDD) has arrived in the PHP community, but for all the talk, there is very little real code. Without being in a training session and with no PHP real examples, learning DDD can be challenging. This book changes all that. It details how to implement tactical DDD patterns and gives full examples of topics such as integrating Bounded Contexts with REST, and DDD messaging strategies. In this book, the authors show you, with tons of details and examples, how to properly design Entities, Value Objects, Services, Domain Events, Aggregates, Factories, Repositories, Services, and Application Services with PHP. They show how to apply Hexagonal Architecture within your application whether you use an open source framework or your own. Carlos Buenosvinos is a PHP Extreme Programmer with more than 15 years of experience developing web applications and more than 10 years experience as a Tech Lead and CTO leading teams of between 20 and 100 people. He is a Certified ScrumMaster (CSM) and has coached and trained close to two dozen different companies in Agile practices, both as an

394 pages, Paperback

Published June 14, 2017

39 people are currently reading
178 people want to read

About the author

Carlos Buenosvinos

2Ìýbooks66Ìýfollowers
Carlos is a PHP Extreme Programmer with more than 15 years of experience developing web applications and more than 10 years experience as a Tech Lead and CTO leading teams of between 20 and 100 people. He is a Certified ScrumMaster (CSM) and has coached and trained close to two dozen different companies in Agile practices, both as an employee and as a consultant. On the technical side, he is a Zend PHP Engineer, a Zend Framework Engineer, and MySQL certified. He is also a board member of the PHP Barcelona User Group. He has worked with e-commerce (Atrapalo and eBay), payment processing (Vendo), classifieds (Emagister), and B2B recruiting tools (XING). He is interested in JavaScript, DevOps, and Scala. He likes developing for mobile, Raspberry Pi, and games.

- Twitter:
- Web:
- GitHub:

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
94 (55%)
4 stars
58 (34%)
3 stars
12 (7%)
2 stars
4 (2%)
1 star
2 (1%)
Displaying 1 - 18 of 18 reviews
Profile Image for Mehrdad.
6 reviews8 followers
May 20, 2020
A great cookbook with a lot of working examples.
1 review
September 21, 2016
Great content and really well explained. The examples are clear and easy to understand. All in all a great book!
Profile Image for Serban Ghita.
9 reviews
October 4, 2016
Sometimes you may go and apply DDD principles in your app and sometimes you might apply some of them. This book clearly explains a lot of terminology and concepts behind DDD. If you want to learn DDD architecture for your PHP apps go and buy it NOW!
Profile Image for Salvador.
8 reviews
June 8, 2018
Concise and with plenty of examples. Concepts are explained clearly and very well reasoned. A good introduction for people who wants to get started with DDD.

Chapters order could be slightly improved, and there are a few erratas here and there, but nothing major
Profile Image for Pedro Gimenez.
21 reviews4 followers
January 2, 2020
Ya leí el libro en sus primeras versiones pero no lo había leído en esta última, modifico el rating que le di de 2 a 4 estrellas. Dejo un breve resumen con algunos apuntes del libro:

El libro habla sobre DDD, una manera de escribir software que nos ayuda a tener éxito entendiendo y construyendo diseños de software. DDD nos provee de herramientas estratégicas y tácticas que nos ayudan a escribir software de alta calidad que alcance los objetivos del negocio.

DDD está basado en tres pilares:
* El lenguaje ubicuo: Expertos de dominio y desarrolladores de software trabajan juntos en construir un lenguaje común en las distintas áreas del negocio.
* Diseño estratégico
* Diseño táctico: Nos provee de herramientas para escribir un software con menos errores y mayor calidad.

Junto al lenguaje ubicuo tenemos los Contextos Delimitados, estos son límites conceptuales en nuestro sistema. El lenguaje ubicuo dentro de un contexto tiene un significado específico que no tiene porqué darse en otro contexto del negocio.

Para construir aplicaciones complejas, uno de los requisitos clave es tener un diseño arquitectónico que encaje con las necesidades de nuestra aplicación. El libro nos dice que una de las ventajas de DDD es que no está atado a ninguna arquitectura en concreto. A continuación, expone algunas arquitecturas que encajan bien con PHP:

* Arquitectura por Capas
* Cada capa está altamente acoplada a sus capas inferiores (UI > Aplicación > Dominio > Infraestructura)

* Arquitectura Hexagonal
* Sigue una estructura similar a la Arquitectura por Capas
* Soluciona el problema del acoplamiento invirtiendo las dependencias utilizando el Principio de Inversión de Dependencias
* El modelo deja de estar acoplado a la infraestructura

* Command Query Responsibility Segregation (CQRS)
* Sigue una estructura similar a la Arquitectura Hexagonal
* Soluciona el problema de tener muchos métodos en los Repositorios tratándolos como parte de la infraestructura
* Separa el modelo en dos:
* Modelo de escritura
* Se encarga de las escrituras
* Toma la responsabilidad sobre el comportamiento del modelo
* Cada vez que alguien lanza un comando, escribe en la persistencia y actualiza el Modelo de Lectura
* Modelo de lectura:
* Se encarga de las lecturas
* Las trata como algo que debe estar fuera del modelo
* La separación en el modelo causa un problema: Consistencia Eventual. El Modelo de Lectura es eventualmente consistente, es decir, hay un retraso entre la actualización del Modelo de Escritura y el Modelo de Lectura
* Los procesos de actualización se llaman Write Model Projections. El proceso puede ser asíncrono o síncrono.
* Implementamos los procesos de actualización a través de Eventos de Dominio

* Event sourcing
* Construye sobre CQRS
* Nos permite tener una sola tabla que guardará todos los Eventos de Dominio
* No precisa de ORM
* Para mejorar la perf. emplea Snapshots de los agregados cada N eventos o cada N segundos.

Otras herramientas de las que habla el libro son las siguientes:
* Value Objects
* Objetos cuya igualdad no está basada en su identidad sino en su contenido, i.e. Money o Date object.
* Características
* Mide, cuantifica o describe algo en el Dominio
* Es inmutable
* Es comparado mediante su valor
* Es completamente reemplazable cuando la cuantía o la descripción cambia
* No tiene efectos secundarios
* Testing
* Como cualquier otro objeto corriente
* Testamos su inmutabilidad
* Persistencia
* Típicamente dentro de un agregado
* Persistir como valor embebido o como LOB serializado

* Entidades
* Objetos con una identidad que permanece con el tiempo, i.e. Orden en un e-commerce
* Utilizar un Value Object como identidad (son inmutables y pueden implementar comportamientos, hacen la operación de igualdad explícita)
* Crean los Eventos de Dominio
* Operación de identidad: cuatro opciones
* Delegar al mecanismo de persistencia (AUTO_INCREMENT)
* Obtenerla del cliente en los dominios en los que tenga sentido (libro y su ISBN)
* Generarla en la aplicación (recomendado si no la obtenemos del cliente). Utilizar UUID. Construimos el Value Object en el Repositorio
* Otro Contexto Delimitado genera la identidad
* Testing
* Testamos las invariantes porque el comportamiento estará creado alrededor de éstas

* Servicios
* Útiles cuando hay operaciones en las que la responsabilidad no caiga sobre Entidades o Value Objects
* Tres tipos de servicios
* Servicios de Aplicación
* Son la capa intermedia entre los clientes y la lógica de dominio. Transforman comandos del exterior en operaciones dentro del dominio
* Reciben y responden con DTOs
* Servicios de Dominio
* Se encargan de operaciones que no encajan bien en Entidades o Value Objects. Sólo manejan tipos del Dominio
* Servicios de Infraestructura
* Operaciones que solucionan problemas de infraestructura, por ejemplo, enviar emails

* Eventos de Dominio
* Eventos relacionados con cambios en el Dominio
* Ayudan a comunicarnos con otros Contextos Delimitados
* Mejoran la perf. forzándonos a tener Consistencia Eventual
* Sirven como histórico
* Representar como verbos en tiempo pasado
* Contienen fecha del evento e identidades de Entidades relacionadas

* Agregados
* Son Entidades que están compuestas de otras Entidades y Value Objects para ayudar a mantener un estado consistente

* Repositorios
* Actúan como lugares de almacenamiento
* Normalmente hay una relación 1:1 con los agregados
* No son DAOs, representan Colecciones
* Specification Pattern para las queries
Profile Image for Eszter Pálmai.
22 reviews13 followers
December 26, 2024
We use this book as a guideline at work. I hate it, I wish we went with the original Eric Evans book instead. This book is full of objectively terrible solutions and shortcuts (Infrastructure layer regularly mingled with the Domain layer for example) and recommends building the application around external library implementation details instead of core business logic. It is also full of code examples, which are prone to becoming obsolete and they are an unnecessary waste of space. DDD really is not language-specific, there was next to no reason to write a book about it specifically for PHP developers to begin with.
Could rant on about how bad this book is indefinitely, but I guess I reserve that to my unfortunate co-workers. TLDR it's very bad. Read Eric Evans or Martin Fowler instead of this.
Profile Image for Murat Gözel.
4 reviews
December 12, 2020
Describes things well. It's not something that documents topics and treating them as meta. It tries to explain the topics. I like to read the opinions and recommendations of experienced programmers about challenging situations.

The title says for PHP but I think anyone who knows more than one programming language can learn domain-driven-design from this book.

My only suggestion is that it would be nicer (or easier to read, easier to connect chapters) if the book starts with Value Objects instead of the design patterns (MVC, CQRS).
1 review
May 22, 2020
That was an awesome read !
Really....

The books explains clearly what Domain Driven Design is, why you should adopt it, how you should implement it what the benefits are, and the pain points and uses excellent real life examples in PHP to illustrate all of this.

I highly recommend this book...
Probably one of the best books on programming in PHP I've read
Profile Image for Marko Kunic.
20 reviews1 follower
August 31, 2018
This book is very good. There are a lot of code examples that will quickly get you into DDD with a lot of familiar code that makes it even easier to understand it. This was my second DDD book only because I mainly work with PHP.
Profile Image for Fermin.
24 reviews2 followers
July 25, 2018
Imprescindible para todos aquellos arquitectos que quieran aplicar DDD en sus proyectos PHP.
Mucho ejemplos de implementación que te resolverán muchas dudas y horas de investigación.
1 review
July 1, 2019
Great book and easy to read. Good examples and amazing explanations. Recommend for anyone in the field.
4 reviews
May 30, 2017
It was first book on DDD I read and I'm happy about it. It's fairly short, concrete and illustrative. It covered basics perfectly and made me want to dive deeper into the subject.
Profile Image for Stan.
4 reviews
January 27, 2017
This book presents a good adaptation of the tactical patterns of DDD for the PHP language. If you are new to DDD, this book may feel alien unfortunately. The core concepts are glanced over and focus is on the code instead. This is somewhat to be expected given DDD in PHP focuses on the building blocks of DDD -- it's worthwhile mentioning for those expecting a full coverage of DDD including the high-level concepts.

To make good use of this book, you should be familiar with Doctrine and Symfony. If you are using a different ORM or no ORM at all (e.g., Active Record or roll-your-own) then it may be difficult to follow through the examples.

The organisation of the chapters can be improved as earlier chapters use concepts introduced and talked about in later ones.

Note the English in this book is «far from perfect» as pointed out by the authors in the acknowledgements.
Profile Image for Libene Fernandes.
122 reviews1 follower
September 1, 2019
“If you don’t understand the Domain you’re working on because it’s new and nobody has invested in a solution before, this might mean it’s complex enough for you to start applying Domain-Driven Design.

A good architecture emphasizes the use-cases and decouples them from peripheral concerns.�
Profile Image for Búza Géza.
1 review1 follower
April 15, 2017
I liked the book in general and can recommend to anyone interested in this topic. It's packed with PHP code examples to help to understand the concepts. Also there are many references to the mentioned topics and principles, so it's very helpful if you haven't heard some of it yet.
Aggregates chapter could be more clear, but it's a tough topic.
The introduction of Hexagonal Architecture was a bit short and fuzzy. Fortunately the appendix helped somewhat.
Profile Image for Adam.
4 reviews1 follower
August 27, 2018
Concise and easy to understand. Great examples of DDD tactical patterns in PHP. If you worked with Symfony and Doctrine before, you will feel like at home.

When it comes to DDD strategic patterns, which this book doesn’t cover, nice companion book could be Domain-Driven Design Distilled written by Vaughn Vernon.
Displaying 1 - 18 of 18 reviews

Can't find what you're looking for?

Get help and learn more about the design.