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

What's hot (20)

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

Viewers also liked (20)

PPT
Mobile marketing cómo implementarlo
Interlat
 
DOCX
Abdellah Mahdar CV
Abdellah Mahdar
 
PDF
Proyecto de Inversión en España - ES
Legalium Bufete de Abogados
 
PDF
Issuu tarifas
Elipsos Internacional
 
PDF
Revista n52
susanaforever
 
PPTX
Memories of WMS G.A.T.E. 8th grade 2010
Andrea L. Wurm
 
PPTX
Barcamp Matej Tomasovsky
Matej Tomašovský
 
PPTX
Foda
lotorules
 
PDF
High-Profile May 2012
High-Profile Monthly
 
PDF
eBRIDGE Toolkit
Aida Abdulah
 
PPS
Victor hu1
Marisagg
 
PDF
imetodo_formacion.pdf
imétodo
 
PDF
C O N T A C T O
quisqueya1
 
PDF
Vietnam Boletín Informativo Octubre 2010
Juan Inoriza
 
PPTX
Tarea en clase diapositivas
Diana Imbaquingo
 
PPSX
Consideraciones consideraciones didacticas para enseñar y jugar
togueda
 
PPTX
Proven Strategies to Leverage Your Customer Community to Grow Your Business
Socious
 
PDF
Catálogo mitsubishi electric aire acondicionado msz fd - msz-ge mfz-ka
Rooibos13
 
PDF
Career Guide International Careers
hanzoh
 
PPTX
Capacitación TFS - Build
Ariel Bender
 
Mobile marketing cómo implementarlo
Interlat
 
Abdellah Mahdar CV
Abdellah Mahdar
 
Proyecto de Inversión en España - ES
Legalium Bufete de Abogados
 
Issuu tarifas
Elipsos Internacional
 
Revista n52
susanaforever
 
Memories of WMS G.A.T.E. 8th grade 2010
Andrea L. Wurm
 
Barcamp Matej Tomasovsky
Matej Tomašovský
 
Foda
lotorules
 
High-Profile May 2012
High-Profile Monthly
 
eBRIDGE Toolkit
Aida Abdulah
 
Victor hu1
Marisagg
 
imetodo_formacion.pdf
imétodo
 
C O N T A C T O
quisqueya1
 
Vietnam Boletín Informativo Octubre 2010
Juan Inoriza
 
Tarea en clase diapositivas
Diana Imbaquingo
 
Consideraciones consideraciones didacticas para enseñar y jugar
togueda
 
Proven Strategies to Leverage Your Customer Community to Grow Your Business
Socious
 
Catálogo mitsubishi electric aire acondicionado msz fd - msz-ge mfz-ka
Rooibos13
 
Career Guide International Careers
hanzoh
 
Capacitación TFS - Build
Ariel Bender
 
Ad

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

PDF
Beyond MVC: from Model to Domain
Jeremy Cook
 
PDF
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Kacper Gunia
 
PDF
Refactoring
Artem Tabalin
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PDF
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
PPTX
PHP from soup to nuts Course Deck
rICh morrow
 
PDF
Dutch PHP Conference 2015 - The quest for global design principles
Matthias Noback
 
PDF
Writing Testable Code
jameshalsall
 
PPT
JavaScript & Dom Manipulation
Mohammed Arif
 
PDF
Hexagonal architecture - message-oriented software design
Matthias Noback
 
PPT
Relentless Refactoring
Mark Rickerby
 
PDF
Hexagonal architecture in PHP
Paulo Victor Gomes
 
PDF
Hexagonal architecture
Alessandro Minoccheri
 
PDF
Streamlining Your Applications with Web Frameworks
guestf7bc30
 
PDF
Living With Legacy Code
Rowan Merewood
 
PDF
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Miguel Gallardo
 
PDF
PHP and Rich Internet Applications
elliando dias
 
PPT
Prersentation
Ashwin Deora
 
Beyond MVC: from Model to Domain
Jeremy Cook
 
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Kacper Gunia
 
Refactoring
Artem Tabalin
 
Nodejs Explained with Examples
Gabriele Lana
 
Nodejsexplained 101116115055-phpapp02
Sunny Gupta
 
PHP from soup to nuts Course Deck
rICh morrow
 
Dutch PHP Conference 2015 - The quest for global design principles
Matthias Noback
 
Writing Testable Code
jameshalsall
 
JavaScript & Dom Manipulation
Mohammed Arif
 
Hexagonal architecture - message-oriented software design
Matthias Noback
 
Relentless Refactoring
Mark Rickerby
 
Hexagonal architecture in PHP
Paulo Victor Gomes
 
Hexagonal architecture
Alessandro Minoccheri
 
Streamlining Your Applications with Web Frameworks
guestf7bc30
 
Living With Legacy Code
Rowan Merewood
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Miguel Gallardo
 
PHP and Rich Internet Applications
elliando dias
 
Prersentation
Ashwin Deora
 
Ad

More from Jeremy Cook (8)

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

Recently uploaded (20)

PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Python basic programing language for automation
DanialHabibi2
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 

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