SlideShare a Scribd company logo
TrueNorthPHP 2014 
Beyond MVC: From 
Model to Domain Jeremy Cook
What is a domain?
“a specified sphere of activity or knowledge.” 
–http://www.oxforddictionaries.com/definition/english/domain
“A domain is a field of study that defines a set of 
common requirements, terminology, and 
functionality for any software program 
constructed to solve a problem…” 
–http://en.wikipedia.org/wiki/Domain_(software_engineering)
What is MVC?
Interaction of MVC Layers 
Model! 
User 
Manipulates 
Controller! 
Uses 
Updates 
View! 
Sees
Interaction of MVC Layers 
User 
Model! 
Controller! 
View!
Problems with ‘web’ MVC 
❖ Easy to muddy responsibilities in the controller! 
❖ Use of the term ‘Model’ is an issue…! 
❖ Offers no guidance in modelling the most critical part of 
our apps: the model or domain
“Model–view–controller (MVC) is a software 
architectural pattern for implementing user 
interfaces.” 
–http://en.wikipedia.org/wiki/Model–view–controller
This talk is about managing 
complexity
Introducing Action Domain 
Responder
What is Action Domain Responder? 
❖ Created by Paul M Jones! 
❖ Web specific refinement of MVC! 
❖ Designed to map more closely to what actually happens 
in the lifecycle of a web request
What is Action Domain Responder? 
❖ Model! 
❖ View! 
❖ Controller
What is Action Domain Responder? 
❖ Controller! 
❖ Model! 
❖ View
What is Action Domain Responder? 
❖ Controller Action! 
❖ Model Domain! 
❖ View Responder
Action 
❖ In ADR an action is mapped to a single class or closure! 
❖ Creates a single place for all code dealing with an action! 
❖ Does not directly create a view or HTTP response
Responder 
❖ ADR recognises that a web response is more than a 
view! 
❖ Action instantiates a responder object and injects 
domain data in it! 
❖ Responder is responsible for generating all aspects of 
the response
Domain 
❖ ADR offers no help on modelling a domain…! 
❖ …but at least Paul calls it a domain!! 
❖ Other patterns later will offer more help here
ADR Example 
<?php! 
! 
interface ActionInterface {! 
public function __construct(ResponderFactoryInterface $factory);! 
public function __invoke(RequestInterface $request);! 
}!
ADR Example 
<?php! 
! 
class FooAction implements ActionInterface {! 
protected $responderFactory;! 
! 
public function __construct(ResponderFactoryInterface $factory) {! 
$this->responderFactory = $factory;! 
}! 
! 
public function __invoke(RequestInterface $request) {! 
//Domain logic here! 
$responder = $this->responderFactory->generateForRequest($request);! 
! 
return $responder();! 
}! 
}!
Further information on ADR 
❖ https://github.com/pmjones/adr
Hexagonal Architecture
Ports and Adapters 
Hexagonal Architecture
What’s wrong with ‘Hexagonal Architecture’? 
❖ Has nothing to do with hexagons! 
❖ Has nothing to do with the number 6! 
❖ Ports and adapters describes what this actually does
What are Ports and Adapters? 
❖ Invented by Alistair Cockburn! 
❖ Architectural pattern for isolating an application from 
it’s inputs.
“Allow an application to equally be driven by 
users, programs, automated test or batch scripts, 
and to be developed and tested in isolation from 
its eventual run-time devices and databases.” 
–Alistair Cockburn
“Allow an application to equally be driven by 
users, programs, automated test or batch scripts, 
and to be developed and tested in isolation from 
its eventual run-time devices and databases.” 
–Alistair Cockburn
Ports and Adapters 
Application
Ports and Adapters 
Application
Ports and Adapters 
Adapters 
Adapters 
Application 
Adapters 
Adapters 
Adapters 
Adapters
Ports and Adapters 
Domain 
Adapters 
Adapters 
Adapters 
Adapters 
Adapters 
Adapters
HTTP Adapter 
<?php! 
! 
class FooAction implements ActionInterface {! 
protected $responderFactory;! 
protected $service;! 
! 
public function __construct(ResponderFactoryInterface $factory, 
ApplicationServiceInterface $service) {! 
$this->responderFactory = $factory;! 
$this->service = $service;! 
}! 
! 
public function __invoke(RequestInterface $request) {! 
$result = $this->service->__invoke($request->getParamsArray());! 
$responder = $this->responderFactory->generateForRequest($request);! 
! 
return $responder($result);! 
}! 
}!
AMQP Adapter 
<?php! 
! 
class FooConsumer implements AMQPConsumer {! 
protected $service;! 
! 
public function __construct(ApplicationServiceInterface $service) {! 
$this->service = $service;! 
}! 
! 
public function __invoke(AMQPMessage $msg) {! 
$data = json_decode($msg->body, true);! 
$result = $this->service->__invoke($data);! 
if ($result->isStatusOk()) {! 
$msg->delivery_info['channel']! 
->basic_ack($msg->delivery_info['delivery_tag']);! 
}! 
}! 
}!
Advantages of Ports and Adapters 
❖ Encapsulation of the domain! 
❖ Allows development of the domain and adapters to 
be independent! 
❖ Allows better end to end testability of the domain! 
❖ Makes it simple to add new entry points to an app
Further information on Ports and Adapters 
❖ The original article introducing ports and adapters: 
http://alistair.cockburn.us/Hexagonal+architecture
Introducing Domain Driven 
Design
What is Domain Driven Design? 
❖ Concept coined by Eric Evans! 
❖ Ideas can be grouped into two related areas:! 
❖ Architectural patterns! 
❖ Object patterns
DDD Interaction Map
Read some books
Architectural patterns
Your app has multiple domains
Ubiquitous language 
❖ Develop a shared language to describe each domain 
and model the software after it! 
❖ The domain should be an expression of the ubiquitous 
language in code! 
❖ Aim is to unite all members of a product team, from 
developers to product managers
Bounded contexts 
❖ Represents the boundary around a domain! 
❖ All code within a domain is completely encapsulated 
with specific entry points! 
❖ Code and concepts are unique per domain
Context map 
❖ Describes relationships between domains! 
❖ Outlines all points of contact between domains! 
❖ Can also include existing systems
Object patterns
Entities 
❖ Represents a concept in your domain! 
❖ Each instance of a entity should be considered unique! 
❖ Houses logic and operation on the concept
Value Objects 
❖ Used when you only care about the attributes and logic 
of the concept! 
❖ Immutable! 
❖ All methods must be side effect free! 
❖ Mutator methods must return a new instance of the 
value object! 
❖ Prefer value objects over simple types
Value Objects 
<?php! 
! 
class Person {! 
public function __construct($firstName, $lastName) {! 
//Code here! 
}! 
}! 
! 
$person = new Person('Cook', 'Jeremy'); //WHOOPS!!
Value Objects 
<?php! 
! 
class Firstname {! 
protected $firstname;! 
! 
public function __construct($firstname) {! 
if (! is_string($firstname)) {! 
throw new InvalidArgumentException(/**ErrorMessage**/);! 
}! 
$this->firstname = $firstname;! 
}! 
! 
public function __toString() {! 
return $this->firstname;! 
}! 
}!
Value Objects 
<?php! 
! 
class Person {! 
public function __construct(Firstname $firstName, Lastname $lastName) {! 
//Code here! 
}! 
}! 
! 
//This will now cause an error! 
$person = new Person(new Lastname('Cook'), new Firstname('Jeremy'));!
Entities vs Value Objects 
!== 
Bank Account 
Owner: Jeremy 
Balance: $1,000,000 
Account #: 12345 
=== 
Currency 
Name: Canadian Dollar 
Abbr: CAD 
Symbol: $ 
Bank Account 
Owner: Jeremy 
Balance: $1,000,000 
Account #: 12346 
Currency 
Name: Canadian Dollar 
Abbr: CAD 
Symbol: $
Aggregates 
❖ A collection of entities contained by another entity! 
❖ The containing entity is the aggregate root! 
❖ Individual aggregate instances can only be accessed 
through the aggregate root
Repositories 
❖ A specialised adapter that maps entities to and from the 
persistence layer! 
❖ Provides methods to retrieve entities and save them! 
❖ Abstracts the details of the persistence layer away from 
the domain
Domain Services 
❖ Encapsulates an operation that is not owned by another 
part of the domain model! 
❖ A good service has three properties:! 
❖ Models a domain concept that does not conceptually 
belong to an entity or value object! 
❖ Stateless! 
❖ Defined in terms of the domain model
Domain Services 
<?php! 
! 
class MoneyTransfer {! 
public static function transferBetweenAccounts(Account $from, Account 
$to, Money $amount) {! 
$from->debitForTransfer($money, $to);! 
$to->creditFromTransfer($money, $from);! 
}! 
}! 
! 
//In the application service...! 
$from = $accountRepository->findByAccNumber('123456');! 
$to = $accountRepository->findByAccNumber('123457');! 
$money = new Money('100', new Currency('CAD'));! 
MoneyTransfer::transferBetweenAccounts($from, $to, $money);!
Domain Events 
❖ Allows a domain to signal that something as happened! 
❖ Full part of the domain and a representation of 
something that has happened! 
❖ Used to signal something that might trigger a state 
change in another domain
Domain Events 
<?php! 
! 
class MoneyTransfer {! 
public static function transferBetweenAccounts(Account $from, Account 
$to, Money $amount) {! 
$from->debitForTransfer($money, $to);! 
$to->creditFromTransfer($money, $from);! 
}! 
}! 
! 
//In the application service...! 
$from = $accountRepository->findByAccNumber('123456');! 
$to = $accountRepository->findByAccNumber('123457');! 
$money = new Money('100', new Currency('CAD'));! 
MoneyTransfer::transferBetweenAccounts($from, $to, $money);! 
$event = EventFactory::createEventForSuccessfulAccountTransfer($from, $to, 
$money);! 
$eventType = EventTypes::SUCCESSFUL_MONEY_TRANSFER;! 
$eventDispatcher->raiseEvent($eventType, $event);
Further Information on DDD 
❖ Eric Evans! 
❖ “Domain Driven Design” book! 
❖ Short introduction: https://domainlanguage.com/ddd/ 
patterns/DDD_Reference_2011-01-31.pdf! 
❖ Implementing Domain Driven Design by Vaughn Vernon! 
❖ Mathias Verraes: http://verraes.net! 
❖ DDD in PHP Google Group: https://groups.google.com/ 
forum/#!forum/dddinphp
Avoid projects like this!
Thanks for listening! 
❖ Any questions?! 
❖ Feel free to contact me! 
❖ jeremycook0@gmail.com! 
❖ @JCook21

More Related Content

PDF
Crafting Quality PHP Applications (PHPkonf 2018)
PDF
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
PDF
Crafting Quality PHP Applications (PHP Benelux 2018)
PDF
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
PDF
Bullet: The Functional PHP Micro-Framework
PDF
Best practices for crafting high quality PHP apps (PHP Yorkshire 2018)
PDF
Crafting Quality PHP Applications (ConFoo YVR 2017)
PDF
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Crafting Quality PHP Applications (PHPkonf 2018)
Crafting Quality PHP Applications (Bucharest Tech Week 2017)
Crafting Quality PHP Applications (PHP Benelux 2018)
Crafting Quality PHP Applications: an overview (PHPSW March 2018)
Bullet: The Functional PHP Micro-Framework
Best practices for crafting high quality PHP apps (PHP Yorkshire 2018)
Crafting Quality PHP Applications (ConFoo YVR 2017)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)

What's hot (20)

PDF
Hello World on Slim Framework 3.x
PDF
The Naked Bundle - Symfony Live London 2014
PDF
How Symfony Changed My Life
PDF
Isomorphic App Development with Ruby and Volt - Rubyconf2014
PDF
Crafting Quality PHP Applications (PHP Joburg Oct 2019)
ODP
Step objects
PDF
Best practices for crafting high quality PHP apps (Bulgaria 2019)
PDF
Volt 2015
PDF
"Managing API Complexity". Matthew Flaming, Temboo
PDF
Keeping it Small: Getting to know the Slim Micro Framework
PDF
Best practices for crafting high quality PHP apps (PHP South Africa 2018)
PDF
Best practices for crafting high quality PHP apps - PHP UK 2019
PDF
Best practices for crafting high quality PHP apps (ScotlandPHP 2018)
PDF
Rails for Beginners - Le Wagon
PDF
Roman Schejbal: From Madness To Reason
PDF
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
PPT
Slim RedBeanPHP and Knockout
PDF
Deliver Business Value Faster with AWS Step Functions
PDF
Don't worry be API with Slim framework and Joomla
KEY
Keeping it small: Getting to know the Slim micro framework
Hello World on Slim Framework 3.x
The Naked Bundle - Symfony Live London 2014
How Symfony Changed My Life
Isomorphic App Development with Ruby and Volt - Rubyconf2014
Crafting Quality PHP Applications (PHP Joburg Oct 2019)
Step objects
Best practices for crafting high quality PHP apps (Bulgaria 2019)
Volt 2015
"Managing API Complexity". Matthew Flaming, Temboo
Keeping it Small: Getting to know the Slim Micro Framework
Best practices for crafting high quality PHP apps (PHP South Africa 2018)
Best practices for crafting high quality PHP apps - PHP UK 2019
Best practices for crafting high quality PHP apps (ScotlandPHP 2018)
Rails for Beginners - Le Wagon
Roman Schejbal: From Madness To Reason
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Slim RedBeanPHP and Knockout
Deliver Business Value Faster with AWS Step Functions
Don't worry be API with Slim framework and Joomla
Keeping it small: Getting to know the Slim micro framework
Ad

Viewers also liked (20)

PPT
Mobile marketing cómo implementarlo
DOCX
Abdellah Mahdar CV
PDF
Proyecto de Inversión en España - ES
PDF
Issuu tarifas
PDF
Revista n52
PPTX
Memories of WMS G.A.T.E. 8th grade 2010
PPTX
Barcamp Matej Tomasovsky
PPTX
Foda
PDF
High-Profile May 2012
PDF
eBRIDGE Toolkit
PPS
Victor hu1
PDF
imetodo_formacion.pdf
PDF
C O N T A C T O
PDF
Vietnam Boletín Informativo Octubre 2010
PPTX
Tarea en clase diapositivas
PPSX
Consideraciones consideraciones didacticas para enseñar y jugar
PPTX
Proven Strategies to Leverage Your Customer Community to Grow Your Business
PDF
Catálogo mitsubishi electric aire acondicionado msz fd - msz-ge mfz-ka
PDF
Career Guide International Careers
PPTX
Capacitación TFS - Build
Mobile marketing cómo implementarlo
Abdellah Mahdar CV
Proyecto de Inversión en España - ES
Issuu tarifas
Revista n52
Memories of WMS G.A.T.E. 8th grade 2010
Barcamp Matej Tomasovsky
Foda
High-Profile May 2012
eBRIDGE Toolkit
Victor hu1
imetodo_formacion.pdf
C O N T A C T O
Vietnam Boletín Informativo Octubre 2010
Tarea en clase diapositivas
Consideraciones consideraciones didacticas para enseñar y jugar
Proven Strategies to Leverage Your Customer Community to Grow Your Business
Catálogo mitsubishi electric aire acondicionado msz fd - msz-ge mfz-ka
Career Guide International Careers
Capacitación TFS - Build
Ad

Similar to Beyond MVC: from Model to Domain (20)

PDF
Beyond MVC: from Model to Domain
PDF
Domain driven design: a gentle introduction
PPT
Domain Driven Design (DDD)
PPTX
Seminar - Scalable Enterprise Application Development Using DDD and CQRS
PPTX
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
PPTX
Refreshing Domain Driven Design
PDF
All the cool kids....
PPTX
Crafted Design - Sandro Mancuso
PPTX
Crafted Design - LJC World Tour Mash Up 2014
PPTX
Software Development: Beyond Training wheels
PPTX
Domain driven design
PDF
What is DDD and how could it help you
PPTX
Implementing DDD Concepts in PHP
PPTX
Brownfield Domain Driven Design
PPTX
Crafted Design - GeeCON 2014
PPTX
An Introduction to Domain Driven Design in PHP
PPTX
Crafted Design - ITAKE 2014
ODP
Into the domain
PPTX
A Practical Guide to Domain Driven Design: Presentation Slides
PDF
IPC07 Talk - Beautiful Code with AOP and DI
Beyond MVC: from Model to Domain
Domain driven design: a gentle introduction
Domain Driven Design (DDD)
Seminar - Scalable Enterprise Application Development Using DDD and CQRS
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Refreshing Domain Driven Design
All the cool kids....
Crafted Design - Sandro Mancuso
Crafted Design - LJC World Tour Mash Up 2014
Software Development: Beyond Training wheels
Domain driven design
What is DDD and how could it help you
Implementing DDD Concepts in PHP
Brownfield Domain Driven Design
Crafted Design - GeeCON 2014
An Introduction to Domain Driven Design in PHP
Crafted Design - ITAKE 2014
Into the domain
A Practical Guide to Domain Driven Design: Presentation Slides
IPC07 Talk - Beautiful Code with AOP and DI

More from Jeremy Cook (8)

PDF
Unit test your java architecture with ArchUnit
PDF
Tracking your data across the fourth dimension
PDF
Tracking your data across the fourth dimension
PDF
Track your data across the fourth dimension
ODP
Accelerate your web app with a layer of Varnish
ODP
Turbo charge your logs
ODP
Turbo charge your logs
PPTX
PHPUnit: from zero to hero
Unit test your java architecture with ArchUnit
Tracking your data across the fourth dimension
Tracking your data across the fourth dimension
Track your data across the fourth dimension
Accelerate your web app with a layer of Varnish
Turbo charge your logs
Turbo charge your logs
PHPUnit: from zero to hero

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Advanced IT Governance
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
Cloud computing and distributed systems.
PDF
cuic standard and advanced reporting.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
The Rise and Fall of 3GPP – Time for a Sabbatical?
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Empathic Computing: Creating Shared Understanding
Sensors and Actuators in IoT Systems using pdf
Advanced IT Governance
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
GamePlan Trading System Review: Professional Trader's Honest Take
madgavkar20181017ppt McKinsey Presentation.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Cloud computing and distributed systems.
cuic standard and advanced reporting.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
CIFDAQ's Market Insight: SEC Turns Pro Crypto
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Telecom Fraud Prevention Guide | Hyperlink InfoSystem

Beyond MVC: from Model to Domain

  • 1. TrueNorthPHP 2014 Beyond MVC: From Model to Domain Jeremy Cook
  • 2. What is a domain?
  • 3. “a specified sphere of activity or knowledge.” –http://www.oxforddictionaries.com/definition/english/domain
  • 4. “A domain is a field of study that defines a set of common requirements, terminology, and functionality for any software program constructed to solve a problem…” –http://en.wikipedia.org/wiki/Domain_(software_engineering)
  • 6. Interaction of MVC Layers Model! User Manipulates Controller! Uses Updates View! Sees
  • 7. Interaction of MVC Layers User Model! Controller! View!
  • 8. Problems with ‘web’ MVC ❖ Easy to muddy responsibilities in the controller! ❖ Use of the term ‘Model’ is an issue…! ❖ Offers no guidance in modelling the most critical part of our apps: the model or domain
  • 9. “Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces.” –http://en.wikipedia.org/wiki/Model–view–controller
  • 10. This talk is about managing complexity
  • 12. What is Action Domain Responder? ❖ Created by Paul M Jones! ❖ Web specific refinement of MVC! ❖ Designed to map more closely to what actually happens in the lifecycle of a web request
  • 13. What is Action Domain Responder? ❖ Model! ❖ View! ❖ Controller
  • 14. What is Action Domain Responder? ❖ Controller! ❖ Model! ❖ View
  • 15. What is Action Domain Responder? ❖ Controller Action! ❖ Model Domain! ❖ View Responder
  • 16. Action ❖ In ADR an action is mapped to a single class or closure! ❖ Creates a single place for all code dealing with an action! ❖ Does not directly create a view or HTTP response
  • 17. Responder ❖ ADR recognises that a web response is more than a view! ❖ Action instantiates a responder object and injects domain data in it! ❖ Responder is responsible for generating all aspects of the response
  • 18. Domain ❖ ADR offers no help on modelling a domain…! ❖ …but at least Paul calls it a domain!! ❖ Other patterns later will offer more help here
  • 19. ADR Example <?php! ! interface ActionInterface {! public function __construct(ResponderFactoryInterface $factory);! public function __invoke(RequestInterface $request);! }!
  • 20. ADR Example <?php! ! class FooAction implements ActionInterface {! protected $responderFactory;! ! public function __construct(ResponderFactoryInterface $factory) {! $this->responderFactory = $factory;! }! ! public function __invoke(RequestInterface $request) {! //Domain logic here! $responder = $this->responderFactory->generateForRequest($request);! ! return $responder();! }! }!
  • 21. Further information on ADR ❖ https://github.com/pmjones/adr
  • 23. Ports and Adapters Hexagonal Architecture
  • 24. What’s wrong with ‘Hexagonal Architecture’? ❖ Has nothing to do with hexagons! ❖ Has nothing to do with the number 6! ❖ Ports and adapters describes what this actually does
  • 25. What are Ports and Adapters? ❖ Invented by Alistair Cockburn! ❖ Architectural pattern for isolating an application from it’s inputs.
  • 26. “Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases.” –Alistair Cockburn
  • 27. “Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases.” –Alistair Cockburn
  • 28. Ports and Adapters Application
  • 29. Ports and Adapters Application
  • 30. Ports and Adapters Adapters Adapters Application Adapters Adapters Adapters Adapters
  • 31. Ports and Adapters Domain Adapters Adapters Adapters Adapters Adapters Adapters
  • 32. HTTP Adapter <?php! ! class FooAction implements ActionInterface {! protected $responderFactory;! protected $service;! ! public function __construct(ResponderFactoryInterface $factory, ApplicationServiceInterface $service) {! $this->responderFactory = $factory;! $this->service = $service;! }! ! public function __invoke(RequestInterface $request) {! $result = $this->service->__invoke($request->getParamsArray());! $responder = $this->responderFactory->generateForRequest($request);! ! return $responder($result);! }! }!
  • 33. AMQP Adapter <?php! ! class FooConsumer implements AMQPConsumer {! protected $service;! ! public function __construct(ApplicationServiceInterface $service) {! $this->service = $service;! }! ! public function __invoke(AMQPMessage $msg) {! $data = json_decode($msg->body, true);! $result = $this->service->__invoke($data);! if ($result->isStatusOk()) {! $msg->delivery_info['channel']! ->basic_ack($msg->delivery_info['delivery_tag']);! }! }! }!
  • 34. Advantages of Ports and Adapters ❖ Encapsulation of the domain! ❖ Allows development of the domain and adapters to be independent! ❖ Allows better end to end testability of the domain! ❖ Makes it simple to add new entry points to an app
  • 35. Further information on Ports and Adapters ❖ The original article introducing ports and adapters: http://alistair.cockburn.us/Hexagonal+architecture
  • 37. What is Domain Driven Design? ❖ Concept coined by Eric Evans! ❖ Ideas can be grouped into two related areas:! ❖ Architectural patterns! ❖ Object patterns
  • 41. Your app has multiple domains
  • 42. Ubiquitous language ❖ Develop a shared language to describe each domain and model the software after it! ❖ The domain should be an expression of the ubiquitous language in code! ❖ Aim is to unite all members of a product team, from developers to product managers
  • 43. Bounded contexts ❖ Represents the boundary around a domain! ❖ All code within a domain is completely encapsulated with specific entry points! ❖ Code and concepts are unique per domain
  • 44. Context map ❖ Describes relationships between domains! ❖ Outlines all points of contact between domains! ❖ Can also include existing systems
  • 46. Entities ❖ Represents a concept in your domain! ❖ Each instance of a entity should be considered unique! ❖ Houses logic and operation on the concept
  • 47. Value Objects ❖ Used when you only care about the attributes and logic of the concept! ❖ Immutable! ❖ All methods must be side effect free! ❖ Mutator methods must return a new instance of the value object! ❖ Prefer value objects over simple types
  • 48. Value Objects <?php! ! class Person {! public function __construct($firstName, $lastName) {! //Code here! }! }! ! $person = new Person('Cook', 'Jeremy'); //WHOOPS!!
  • 49. Value Objects <?php! ! class Firstname {! protected $firstname;! ! public function __construct($firstname) {! if (! is_string($firstname)) {! throw new InvalidArgumentException(/**ErrorMessage**/);! }! $this->firstname = $firstname;! }! ! public function __toString() {! return $this->firstname;! }! }!
  • 50. Value Objects <?php! ! class Person {! public function __construct(Firstname $firstName, Lastname $lastName) {! //Code here! }! }! ! //This will now cause an error! $person = new Person(new Lastname('Cook'), new Firstname('Jeremy'));!
  • 51. Entities vs Value Objects !== Bank Account Owner: Jeremy Balance: $1,000,000 Account #: 12345 === Currency Name: Canadian Dollar Abbr: CAD Symbol: $ Bank Account Owner: Jeremy Balance: $1,000,000 Account #: 12346 Currency Name: Canadian Dollar Abbr: CAD Symbol: $
  • 52. Aggregates ❖ A collection of entities contained by another entity! ❖ The containing entity is the aggregate root! ❖ Individual aggregate instances can only be accessed through the aggregate root
  • 53. Repositories ❖ A specialised adapter that maps entities to and from the persistence layer! ❖ Provides methods to retrieve entities and save them! ❖ Abstracts the details of the persistence layer away from the domain
  • 54. Domain Services ❖ Encapsulates an operation that is not owned by another part of the domain model! ❖ A good service has three properties:! ❖ Models a domain concept that does not conceptually belong to an entity or value object! ❖ Stateless! ❖ Defined in terms of the domain model
  • 55. Domain Services <?php! ! class MoneyTransfer {! public static function transferBetweenAccounts(Account $from, Account $to, Money $amount) {! $from->debitForTransfer($money, $to);! $to->creditFromTransfer($money, $from);! }! }! ! //In the application service...! $from = $accountRepository->findByAccNumber('123456');! $to = $accountRepository->findByAccNumber('123457');! $money = new Money('100', new Currency('CAD'));! MoneyTransfer::transferBetweenAccounts($from, $to, $money);!
  • 56. Domain Events ❖ Allows a domain to signal that something as happened! ❖ Full part of the domain and a representation of something that has happened! ❖ Used to signal something that might trigger a state change in another domain
  • 57. Domain Events <?php! ! class MoneyTransfer {! public static function transferBetweenAccounts(Account $from, Account $to, Money $amount) {! $from->debitForTransfer($money, $to);! $to->creditFromTransfer($money, $from);! }! }! ! //In the application service...! $from = $accountRepository->findByAccNumber('123456');! $to = $accountRepository->findByAccNumber('123457');! $money = new Money('100', new Currency('CAD'));! MoneyTransfer::transferBetweenAccounts($from, $to, $money);! $event = EventFactory::createEventForSuccessfulAccountTransfer($from, $to, $money);! $eventType = EventTypes::SUCCESSFUL_MONEY_TRANSFER;! $eventDispatcher->raiseEvent($eventType, $event);
  • 58. Further Information on DDD ❖ Eric Evans! ❖ “Domain Driven Design” book! ❖ Short introduction: https://domainlanguage.com/ddd/ patterns/DDD_Reference_2011-01-31.pdf! ❖ Implementing Domain Driven Design by Vaughn Vernon! ❖ Mathias Verraes: http://verraes.net! ❖ DDD in PHP Google Group: https://groups.google.com/ forum/#!forum/dddinphp
  • 60. Thanks for listening! ❖ Any questions?! ❖ Feel free to contact me! ❖ [email protected]! ❖ @JCook21