SlideShare a Scribd company logo
1 of 26
Download to read offline
What is
DDD
and how could it help you
Luis Henrique Mulinari
luismulinari
luis.mulinari@gmail.com
Frameworks PHP
Symphony
CakePHP
CodeIgniter
LarvalSilex
Yii
PhalconZend Framework Nette
Kohana
SGBD and others SQLite
Eloquent
NoSQL
Larval
Doctrine
SQL
SybaseMySQLMongoDB
PDO
Interfaces Command Line Web Browser APIs
ORM
Active Record
What do they all have in
common?
and
All these tools were/are/will
be the “best choice”
Your domain should not worry
about that
Domain-driven design
BasketWasCreated or BasketWasPickedUp
Concept created by Eric Evans (2003)
It is an approach of software development, designed to work with complex
and large scaled software
It proposes an Ubiquitous language between business and software
(developers and business experts)
It focuses on domain and business
When should we use it?
When should we not use it?
Complex domain with many business rules
Iterative process with a long lifecycle
Growth forecast of complexity
Simple domains (like CRUDs)
Why do we use it?
Agile, iterative and continuous modelling
Less coupling, more cohesive, flexible and extensible code
Testable Code
Agreement between domain experts and developers
BDD tests close to the code
Software for everyone to understand
Domain-driven design
DDD and PHP
ORM
Dependency Injection
UUID
Frameworks
Other tools
Entities
Have an identity that endures over the time
1 class User {
2 private $username;
3 private $password;
4
5 public function getUsername() : string {
6 return $this->username;
7 }
8
9 public function setUsername(string $username) {
10 $this->username = $username;
11 }
12
13 public function getPassword() : string {
14 return $this->password;
15 }
16
17 public function setPassword(string $password) {
18 $this->password = $password;
19 }
20 }
Don’t forget the PSR-1 :P
Entities
Entities have behaviourEntities aren't typed arrays (getters e setters)
1 class User {
2 private $banned;
3 private $username;
4 private $passwordHash;
5
6 public function toNickname() : string {
7 return $this->username;
8 }
9
10 public function authenticate(string $pass, callable $checkHash) : bool {
11 return $checkHash($pass, $this->passwordHash)
12 && ! $this->hasActiveBans();
13 }
14
15 public function changePass(string $pass, callable $hash) {
16 $this->passwordHash = $hash($pass);
17 }
18 }
beberlei/assert - Thin assertion library for use in libraries and business-model
Entities
Keep collections hidden in your entities
Disallow Collection access from outside the entity
1 public function banUser(Uuid $userId)
2 {
3 $user = $this->repository->find($userId);
4
5 $user->getBans()->add(new Ban($user));
6 }
1 class User
2 {
3 private $bans;
4
5 public function getBans() : Collection {
6 return $this->bans;
7 }
8 }
1 class User
2 {
3 private $roles;
4
5 public function promote(Role $role) {
6 $this->roles[] = $role;
7 }
8
9 public function is(Role $role) : bool {
10 return $this->roles->has($role);
11 }
12 }
Entities
1 class User {
2 private $id;
3 private $username;
4
5 public function __construct(string $username) {
6 $this->id = Uuid::uuid4();
7 $this->username = $username;
8 }
9 }
Your db operations will block each other
You are denying bulk inserts
You cannot make multi-request transactions
Your object is invalid until saved
Your object does not work without the DB
Immutable data is simple
Immutable data is cacheable (forever)
Immutable data is predictable
Immutable data enables historical analysis
Or append-only data-structures
Avoid Auto-generated Identifiers Stay valid after __construct
Avoid Soft-deletes
Avoid setters
DateTimeImmutable
More expressive
Easier to test
Less coupling
More flexible
Easier to refactor
Value Objects
Martin Fowler defines a Value Object as a small object such as money or a date range object.
Examples: numbers, text strings, dates, times, a person’s full name (composed
of first, middle, last name, and title), currencies, colours, phone numbers, and postal code.
1 class Email {
2 public function __construct($email) {
3 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
4 throw new InvalidArgumentException('...');
5 }
6
7 $this->email = $email;
8 }
9
10 public function __toString() : string {
11 return $this->email;
12 }
13 }
ValueObjects ensure consistency Immutability Validate your data
Aggregates
Martin Fowler defines Aggregates as a cluster of domain objects that can be treated as a
single unit.
Aggregates are all about transactions.
1 class Order {
2 function __construct(
3 Customer $customer,
4 ProductList $productList
5 ) {
6 $this->id = Uuid::uuid4();
7 $this->customer = $customer;
8 $this->productList = $productList;
9 $this->status = Status::open();
10 }
11
12 public function getTotal() {
13 // ...
14 }
15
16 // ...
17 }
Repositories
1 interface OrderRepository {
2 public function findById($id) : Order;
3
4 public function findByUser(User $user) : ArrayCollection;
5 }
Repositories act as storage locations, where a retrieved object is returned
in the exact same state it was persisted
1 class DoctrineOrderRepository implements OrderRepository { }
2
3 class FileOrderRepository implements OrderRepository { }
4
5 class InMemoryOrderRepository implements OrderRepository { }
Infrastructure Layer
Prefer Query Functions
Factories
Factories help in decoupling the client from knowing how to build complex
objects and Aggregates
1 class ComplexObjectFactory {
2
3 public function create (
4 User $user,
5 ProductList $productList,
6 ShipAddress $shipAddress
7 ) {
8 $object = new Object(...);
9
10 // complex logic
11
12 return $object;
13 }
14 }
15
Services
When there are operations
that need to be represented,
we can consider them to be
services
1 class OrderCreator {
2
3 /**
4 * @var EntityManagerInterface
5 */
6 private $entityManager;
7
8 /**
9 * @var EventDispatcherInterface
10 */
11 private $eventDispatcher;
12
13 public function create(
14 Customer $customer,
15 ProductList $productList
16 ) : Order {
17 $order = $this->factory->create(...);
18
19 // ... some domain validations
20
21 $this->entityManager->persist($order);
22
23 $this->eventDispatcher->dispatch(
24 OrderEvent::CREATED,
25 new OrderEvent($order)
26 );
27
28 // ...
29
30 return $order;
31 }
32 }
CouponDiscount = null
Prefer NullObject Pattern
Command Patter
Ubiquitous Language
1 $command = new SuspendCustomer($customer);
2
3 $commandBus->handle($command);
Commands express intend (user actions)
Commands are simple
Commands are Value Objects
CQRS
Command-Query Responsibility Segregation
Read Write
90% 10%
ViewModels / Flexible
Eventually consistent
Validation / Business rules
Coherence (ACID)
CQRS
Overview
and
All those tools were/are/will
be the “best choice”
Your domain should not worry
about that
Thanks!
Questions?
Credits and References
Luís Otávio Cobucci Oblonczyk
Domain-driven Design - Eric Evans
Patterns of Enterprise Application Architecture - Martin Folwer
Mathias Verraes
Domain-Driven Design in PHP
Carlos Buenosvinos, Christian Soronellas and Keyvan Akbary
Marco Pivetta
Isabel Janke <3

More Related Content

What's hot

ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
Jonathan Wage
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 
psnreddy php-oops
psnreddy  php-oopspsnreddy  php-oops
psnreddy php-oops
satya552
 

What's hot (20)

Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Closer look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin ShenoiCloser look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin Shenoi
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
 
[2019] Spring JPA의 사실과 오해
[2019] Spring JPA의 사실과 오해[2019] Spring JPA의 사실과 오해
[2019] Spring JPA의 사실과 오해
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
What's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field APIWhat's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field API
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
psnreddy php-oops
psnreddy  php-oopspsnreddy  php-oops
psnreddy php-oops
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 

Viewers also liked

Why Domain-Driven Design and Reactive Programming?
Why Domain-Driven Design and Reactive Programming?Why Domain-Driven Design and Reactive Programming?
Why Domain-Driven Design and Reactive Programming?
VMware Tanzu
 

Viewers also liked (20)

Domain-Driven Design und Hexagonale Architektur
Domain-Driven Design und Hexagonale ArchitekturDomain-Driven Design und Hexagonale Architektur
Domain-Driven Design und Hexagonale Architektur
 
Domain-Driven Design workshops
Domain-Driven Design workshopsDomain-Driven Design workshops
Domain-Driven Design workshops
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Domain-driven design - tactical patterns
Domain-driven design - tactical patternsDomain-driven design - tactical patterns
Domain-driven design - tactical patterns
 
From legacy to DDD
From legacy to DDDFrom legacy to DDD
From legacy to DDD
 
Ddd reboot (english version)
Ddd reboot (english version)Ddd reboot (english version)
Ddd reboot (english version)
 
CQRS and what it means for your architecture
CQRS and what it means for your architectureCQRS and what it means for your architecture
CQRS and what it means for your architecture
 
CQRS
CQRSCQRS
CQRS
 
Our way to microservices
Our way to microservicesOur way to microservices
Our way to microservices
 
Modelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven DesignModelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven Design
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)
 
Designing APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven DesignDesigning APIs and Microservices Using Domain-Driven Design
Designing APIs and Microservices Using Domain-Driven Design
 
Why Domain-Driven Design and Reactive Programming?
Why Domain-Driven Design and Reactive Programming?Why Domain-Driven Design and Reactive Programming?
Why Domain-Driven Design and Reactive Programming?
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slides
 
Tactical DDD (just better OOP?) - PHPBenelux 2017
Tactical DDD (just better OOP?) - PHPBenelux 2017Tactical DDD (just better OOP?) - PHPBenelux 2017
Tactical DDD (just better OOP?) - PHPBenelux 2017
 
Architecting Microservices in .Net
Architecting Microservices in .NetArchitecting Microservices in .Net
Architecting Microservices in .Net
 
The art of Software Design
The art of Software DesignThe art of Software Design
The art of Software Design
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 

Similar to What is DDD and how could it help you

Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
Sameer Poudel
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 

Similar to What is DDD and how could it help you (20)

Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
Framework agnostic application Will it fit with Symfony? - Symfony live warsa...
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EE
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
 
Repository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelRepository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir Poudel
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

What is DDD and how could it help you

  • 1. What is DDD and how could it help you
  • 3. Frameworks PHP Symphony CakePHP CodeIgniter LarvalSilex Yii PhalconZend Framework Nette Kohana SGBD and others SQLite Eloquent NoSQL Larval Doctrine SQL SybaseMySQLMongoDB PDO Interfaces Command Line Web Browser APIs ORM Active Record What do they all have in common?
  • 4. and All these tools were/are/will be the “best choice” Your domain should not worry about that
  • 5. Domain-driven design BasketWasCreated or BasketWasPickedUp Concept created by Eric Evans (2003) It is an approach of software development, designed to work with complex and large scaled software It proposes an Ubiquitous language between business and software (developers and business experts) It focuses on domain and business
  • 6. When should we use it? When should we not use it? Complex domain with many business rules Iterative process with a long lifecycle Growth forecast of complexity Simple domains (like CRUDs)
  • 7. Why do we use it? Agile, iterative and continuous modelling Less coupling, more cohesive, flexible and extensible code Testable Code Agreement between domain experts and developers BDD tests close to the code Software for everyone to understand
  • 9. DDD and PHP ORM Dependency Injection UUID Frameworks Other tools
  • 10. Entities Have an identity that endures over the time 1 class User { 2 private $username; 3 private $password; 4 5 public function getUsername() : string { 6 return $this->username; 7 } 8 9 public function setUsername(string $username) { 10 $this->username = $username; 11 } 12 13 public function getPassword() : string { 14 return $this->password; 15 } 16 17 public function setPassword(string $password) { 18 $this->password = $password; 19 } 20 } Don’t forget the PSR-1 :P
  • 11. Entities Entities have behaviourEntities aren't typed arrays (getters e setters) 1 class User { 2 private $banned; 3 private $username; 4 private $passwordHash; 5 6 public function toNickname() : string { 7 return $this->username; 8 } 9 10 public function authenticate(string $pass, callable $checkHash) : bool { 11 return $checkHash($pass, $this->passwordHash) 12 && ! $this->hasActiveBans(); 13 } 14 15 public function changePass(string $pass, callable $hash) { 16 $this->passwordHash = $hash($pass); 17 } 18 } beberlei/assert - Thin assertion library for use in libraries and business-model
  • 12. Entities Keep collections hidden in your entities Disallow Collection access from outside the entity 1 public function banUser(Uuid $userId) 2 { 3 $user = $this->repository->find($userId); 4 5 $user->getBans()->add(new Ban($user)); 6 } 1 class User 2 { 3 private $bans; 4 5 public function getBans() : Collection { 6 return $this->bans; 7 } 8 } 1 class User 2 { 3 private $roles; 4 5 public function promote(Role $role) { 6 $this->roles[] = $role; 7 } 8 9 public function is(Role $role) : bool { 10 return $this->roles->has($role); 11 } 12 }
  • 13. Entities 1 class User { 2 private $id; 3 private $username; 4 5 public function __construct(string $username) { 6 $this->id = Uuid::uuid4(); 7 $this->username = $username; 8 } 9 } Your db operations will block each other You are denying bulk inserts You cannot make multi-request transactions Your object is invalid until saved Your object does not work without the DB Immutable data is simple Immutable data is cacheable (forever) Immutable data is predictable Immutable data enables historical analysis Or append-only data-structures Avoid Auto-generated Identifiers Stay valid after __construct Avoid Soft-deletes Avoid setters DateTimeImmutable
  • 14. More expressive Easier to test Less coupling More flexible Easier to refactor
  • 15. Value Objects Martin Fowler defines a Value Object as a small object such as money or a date range object. Examples: numbers, text strings, dates, times, a person’s full name (composed of first, middle, last name, and title), currencies, colours, phone numbers, and postal code. 1 class Email { 2 public function __construct($email) { 3 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 4 throw new InvalidArgumentException('...'); 5 } 6 7 $this->email = $email; 8 } 9 10 public function __toString() : string { 11 return $this->email; 12 } 13 } ValueObjects ensure consistency Immutability Validate your data
  • 16. Aggregates Martin Fowler defines Aggregates as a cluster of domain objects that can be treated as a single unit. Aggregates are all about transactions. 1 class Order { 2 function __construct( 3 Customer $customer, 4 ProductList $productList 5 ) { 6 $this->id = Uuid::uuid4(); 7 $this->customer = $customer; 8 $this->productList = $productList; 9 $this->status = Status::open(); 10 } 11 12 public function getTotal() { 13 // ... 14 } 15 16 // ... 17 }
  • 17. Repositories 1 interface OrderRepository { 2 public function findById($id) : Order; 3 4 public function findByUser(User $user) : ArrayCollection; 5 } Repositories act as storage locations, where a retrieved object is returned in the exact same state it was persisted 1 class DoctrineOrderRepository implements OrderRepository { } 2 3 class FileOrderRepository implements OrderRepository { } 4 5 class InMemoryOrderRepository implements OrderRepository { } Infrastructure Layer Prefer Query Functions
  • 18. Factories Factories help in decoupling the client from knowing how to build complex objects and Aggregates 1 class ComplexObjectFactory { 2 3 public function create ( 4 User $user, 5 ProductList $productList, 6 ShipAddress $shipAddress 7 ) { 8 $object = new Object(...); 9 10 // complex logic 11 12 return $object; 13 } 14 } 15
  • 19. Services When there are operations that need to be represented, we can consider them to be services 1 class OrderCreator { 2 3 /** 4 * @var EntityManagerInterface 5 */ 6 private $entityManager; 7 8 /** 9 * @var EventDispatcherInterface 10 */ 11 private $eventDispatcher; 12 13 public function create( 14 Customer $customer, 15 ProductList $productList 16 ) : Order { 17 $order = $this->factory->create(...); 18 19 // ... some domain validations 20 21 $this->entityManager->persist($order); 22 23 $this->eventDispatcher->dispatch( 24 OrderEvent::CREATED, 25 new OrderEvent($order) 26 ); 27 28 // ... 29 30 return $order; 31 } 32 } CouponDiscount = null Prefer NullObject Pattern
  • 20. Command Patter Ubiquitous Language 1 $command = new SuspendCustomer($customer); 2 3 $commandBus->handle($command); Commands express intend (user actions) Commands are simple Commands are Value Objects
  • 21. CQRS Command-Query Responsibility Segregation Read Write 90% 10% ViewModels / Flexible Eventually consistent Validation / Business rules Coherence (ACID)
  • 22. CQRS
  • 24. and All those tools were/are/will be the “best choice” Your domain should not worry about that
  • 26. Credits and References Luís Otávio Cobucci Oblonczyk Domain-driven Design - Eric Evans Patterns of Enterprise Application Architecture - Martin Folwer Mathias Verraes Domain-Driven Design in PHP Carlos Buenosvinos, Christian Soronellas and Keyvan Akbary Marco Pivetta Isabel Janke <3