SlideShare a Scribd company logo
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

Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
Marco Vito Moscaritolo
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
jeromevdl
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
Jonathan Wage
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
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
Cysinfo Cyber Security Community
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
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
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
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
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
Attila Jenei
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
marcingy
 
[2019] Spring JPA의 사실과 오해
[2019] Spring JPA의 사실과 오해[2019] Spring JPA의 사실과 오해
[2019] Spring JPA의 사실과 오해
NHN FORWARD
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
 
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
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
Benjamin Eberlei
 
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
Drupalize.Me
 
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
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
Julio Martinez
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 

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

Domain-Driven Design und Hexagonale Architektur
Domain-Driven Design und Hexagonale ArchitekturDomain-Driven Design und Hexagonale Architektur
Domain-Driven Design und Hexagonale Architektur
Torben Fojuth
 
Domain-Driven Design workshops
Domain-Driven Design workshopsDomain-Driven Design workshops
Domain-Driven Design workshops
Mariusz Kopylec
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
jstack
 
Domain-driven design - tactical patterns
Domain-driven design - tactical patternsDomain-driven design - tactical patterns
Domain-driven design - tactical patterns
Tom Janssens
 
From legacy to DDD
From legacy to DDDFrom legacy to DDD
From legacy to DDD
Andrzej Krzywda
 
Ddd reboot (english version)
Ddd reboot (english version)Ddd reboot (english version)
Ddd reboot (english version)
Thomas Pierrain
 
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
Richard Banks
 
CQRS
CQRSCQRS
Our way to microservices
Our way to microservicesOur way to microservices
Our way to microservices
Andi Pangeran
 
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
Naeem Sarfraz
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
Mustafa Dağdelen
 
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)
Chris Richardson
 
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
LaunchAny
 
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
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
Tung Nguyen Thanh
 
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
thinkddd
 
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
Matthias Noback
 
Architecting Microservices in .Net
Architecting Microservices in .NetArchitecting Microservices in .Net
Architecting Microservices in .Net
Richard Banks
 
The art of Software Design
The art of Software DesignThe art of Software Design
The art of Software Design
Thomas Pierrain
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
wajrcs
 

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

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!
Kacper Gunia
 
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
3camp
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets
 
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...
Dariusz Drobisz
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Alena Holligan
 
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
Rodrigo Cândido da Silva
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
Lorna Mitchell
 
Hexagonal architecture in PHP
Hexagonal architecture in PHPHexagonal architecture in PHP
Hexagonal architecture in PHP
Paulo Victor Gomes
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
Sameer Poudel
 
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
Sameer Poudel
 
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
SWIFTotter Solutions
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
Philip Norton
 
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
Tricode (part of Dept)
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
Raf Kewl
 
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
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Lorna Mitchell
 
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
Neil Crookes
 
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...
go_oh
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 

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
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
 
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
 
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

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 

Recently uploaded (20)

原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 

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