SlideShare ist ein Scribd-Unternehmen logo
1 von 56
An Introduction to Domain
Driven Design
in PHP
Chris Renner
Nashville PHP Meetup
August 9, 2016
Agenda
• A bit about me & what I do
• Describe our principle application and its purpose
• High-level DDD concepts
• Implementation strategies and patterns
• Lessons learned
• Conclusion
About Me - Personal
• Married 17 years with two little ones (10 and 3)
• In Nashville 18 years, originally from Kentucky
• Interests: Too many!
The Renners
About Me - Professional
• Sr. Application Developer at VUMC, 12 years at
Vanderbilt,~10 years as PHP dev
• Self-taught developer*
• internal-facing enterprise scale apps
• Prior: proposal writer, contract negotiator
What I do
• Application Development
• User interaction & support
• Business Analysis
• Reporting and analytics
• Support one enterprise app, a few small apps and a
couple of websites
Our Main App
• PEER
• Went online July 2007
• Primary business application of a department of 30
users, with hundreds of other “customers”.
• Domain is “Contract Management”
What is DDD?
• A set of solutions to documenting, solving and
managing the complexity of business problems in
your code.
• A methodology for thinking and talking about
solving business problems with code
DDD is not…
• a TV show on Food Network
• anything to do with domain names or DNS
• code, but rather principles and practices.
• MVC or an MVC replacement.
• a design pattern.
• an all-or-nothing proposition.
DDD is…
• a process
• modeling business logic in code
• a common language among devs and stakeholders
• agile*
When to use?
• Complicated business logic
• Large code base
• Multiple devs
• Long dev cycle, app lifecycle
• moving paper/human processes into an electronic
system
When NOT to use?
• Short development cycle
• Microservices
• Simple business models
• Minimal business logic
Requirements
• General intelligence - must understand client’s
business process
• Communication skills - must be able to translate biz
speak to tech speak and vice versa
• Humility
The Big Picture
Domain
• A sphere of knowledge, influence or activity. The
subject area to which the user applies a program is
the domain of the software
• e.g. Used Car Sales, Patient Medical Records,
Contract Management*
• not Automotive, Health Care
Model
• A software abstraction representing a specific
concept in the domain.
• Data & Biz Logic
• Will be continually refined as understanding of
domain grows.
Ubiquitous Language
• Ubiquitous: omnipresent, everywhere
• Set of terms structured around the domain model
and used by both tech and biz team members when
discussing the project.
• Use in the code
Bounded Context
• Limits drawn around the scope of the business
problem create a context area.
• Statements about a model can only be understood
within this context.
“Tactical” DDD
Entities
• e.g. Car, Patient, Invoice, Contract
• Typically 1-class per entity
• Mimic real objects
• Data + Business Logic = Domain Models
class Widget {
public $id;
public $price;
public function __construct()
{
}
public function isDiscountable()
{
// logic here
}
}
Factories
• Objects that create instances of other objects
• TIP: Pass in an ID to get back hydrated instance
class Widget
{
public static function factory($id = null)
{
// create instance
$obj = new Widget();
// hydrate with data from persistence
if ($id) {
WidgetMapper::hydrate($obj, $id);
}
return $obj;
}
}
$foo = Widget::factory(1234);
Aggregates
• One-to-Many
• E.g. Entity “Invoice” may have multiple line items,
each probably a LineItem Entity
• Roll up many like things into a parent
Domain Services
• Use sparingly!
• Capture business logic that operates on more than
one entity/model
• When a class isn’t a “thing”
• != application services
Domain Events
• Real actions, events or activities in the business
• Becomes your domain logic
• Place in model/entity or service layer
Modules
• Separate code into meaningful subject areas based
on business logic
• One module for system/application
support/architectural stuff, then modules for each
business sub-area or bundle of related code
• Personal preference
Layers
(Hexagonal Architecture)
• Separation of concerns
• Outer later is interface, either UI or service
connections
• middle layer that translates requests into business
actions
• inner layer is business logic
Patterns and Best Practices
Domain Models
• Implementation of Entity
• Use Inheritance and/or Traits & Interfaces to
abstract and re-use
• Domain Model + Mapper + Table Data Gateway
patterns
Domain
Model
Mapper Table
• All SQL in Table class
• Mapper translates between Model properties and
table column
• Model has NO awareness of the Table class
• Application code (controllers, services) interact
with the Model only
class Widget extends DomainModelAbstract
{
public $id;
public $name;
public $price;
protected $department;
public static function factory($id = null)
{
// create instance
$obj = new Widget();
// hydrate with data from persistence
if ($id) {
WidgetMapper::hydrate($obj, $id);
}
return $obj;
}
}
class WidgetTable extends TableAbstract
{
public $name = ‘WIDGET_TABLE’;
public $primary = ‘ID’;
public function fetchById($id)
{
$sql = “SELECT * FROM $this->name WHERE
$this->primary = :id”;
$result = $db->query($sql, [‘:id’ = > $id]);
return $result->fetch();
}
}
class WidgetMapper extends MapperAbstract
{
public static $columns =
[
‘id’ => ‘ID’,
‘name’ => ‘NAME,
‘price’ => ‘PRICE’
]
}
Interacting with a Domain
Model Instance
$myWidget = Widget::factory();
$myWidget->setName(‘Acme Super Thingy’);
$myWidget->price = 99.95;
$id = $myWidget->save();
echo $id; // 1234
Lazy Loading
class Widget
{
public $deptId;
private $department;
public function getDept()
{
if (!$this->department) {
$this->department = Department::factory($this->deptId);
}
return $this->department;
}
}
echo $widget->getDept()->name; // Human Resources
Getters and Setters
• Don’t Overuse!
• Opportunity to Add Logic
public function setName($string)
{
$this->name = substr($string, 5, 100);
}
public function setStatus($status)
{
if($status != $this->status) {
$this->addtoStatusLog($status);
}
$this->status = $status;
}
Strategy Pattern
• aka “Policy Pattern”
• encapsulate business rules/logic
Strategy Pattern Example
class Contract
{
public function isExpired()
{
if(strtotime($this->endDate) < time()) {
return true;
}
return false;
}
}
$contract->setEndDate(‘2016-08-01’);
echo $contract->isExpired(); // true
Specification Pattern
• like Strategy, but a separate class instead of a
function
• single public function isSatisfiedBy() determines if
an object meets specified criteria
• can be chained
Specification Pattern Example
class BillingAgreementSpecification
{
public function isSatisfiedBy(Contract $contract)
{
if(!$contract->requirementA) {
return false;
}
if(!$contract->requirementB) {
return false;
}
return true;
}
}
$spec = new BillingAgreementSpecification();
echo $spec->isSatisfiedBy($contract); // true
Lessons Learned
Intention-Revealing Interface
• Contextually Relevant Variable, Function and Class
Names
• public function sendFullyExecutedEmail()
Comment Your Code
• comment and docblock everything
IDs for Everything!
• usernames and emails are NOT unique IDs!
• give everything an internal numeric ID, even if its
never seen by user
Minimize Shortcuts
• Code it to work first, then go back and make it right
• hack-y code will bite you later
• iterate + feedback, don’t assume you fully
understand the problem - the Model will never be
“done”
Avoid Framework Lock-In
• Preference for components
• Composer
• Consider extending a Micro-Framework v. an all-in-
one package
Good OOP required
• Abstraction
• Encapsulation
• Separation of Concerns
Avoid Unnecessary
Complexity
• Ask “is this necessary?”
• Don’t let DDD rules become a prison
• Simplicity = Maintainability
Become the Expert
• You will uncover flaws and inefficiencies in the
business logic
• You may end up understanding the business
process better than stakeholders
Summary
• DDD a way of communicating and thinking about a
complex business problem
• Implementing DDD involves the best of enterprise
design patterns, OOP and clean code principles.
• Use what works, every project is different
References
• Domain Driven Design: Tackling Complexity in the Heart of
Software - Eric Evans, 2003
• DDD Reference - Eric Evans,
https://www.domainlanguage.com/ddd/reference/
• Clean Code: A Handbook of Agile Software Craftsmanship -
Robert Martin, 2008
• Patterns of Enterprise Application Architecture - Martin Fowler,
2002
• phproundtable: Domain Driven Design in PHP -
https://www.phproundtable.com/episode/domain-driven-design-
in-php
Find Me
• Twitter: @rennerchris
• Web: www.chrisrenner.com
• Email: rennercr@gmail.com
I’m Troy McClure, and you
might remember me from
such tech talks as “Creating
Legacy Code” and
“Maximizing Technical
Debt”
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Difference between frontend and backend
Difference between frontend and backendDifference between frontend and backend
Difference between frontend and backendRahul Rana
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developerSudhirVarpe1
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptxFalgunSorathiya
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Clean architecture
Clean architectureClean architecture
Clean architecture.NET Crowd
 
Flutter state management from zero to hero
Flutter state management from zero to heroFlutter state management from zero to hero
Flutter state management from zero to heroAhmed Abu Eldahab
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural PatternsSameh Deabes
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in androidPrawesh Shrestha
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design QuicklyMariam Hakobyan
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introductionshaojung
 

Was ist angesagt? (20)

Difference between frontend and backend
Difference between frontend and backendDifference between frontend and backend
Difference between frontend and backend
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developer
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
reactJS
reactJSreactJS
reactJS
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Seminar report
Seminar reportSeminar report
Seminar report
 
Flutter state management from zero to hero
Flutter state management from zero to heroFlutter state management from zero to hero
Flutter state management from zero to hero
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Event handling
Event handlingEvent handling
Event handling
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Domain Driven Design Quickly
Domain Driven Design QuicklyDomain Driven Design Quickly
Domain Driven Design Quickly
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 

Ähnlich wie An Introduction to Domain Driven Design in PHP

Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introductionwojtek_s
 
A Case for Outside-In Design
A Case for Outside-In DesignA Case for Outside-In Design
A Case for Outside-In DesignSandro Mancuso
 
MODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeMODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeHussein Alshkhir
 
Schibsted Spain - Day 1 - DDD Course
Schibsted Spain - Day 1 - DDD CourseSchibsted Spain - Day 1 - DDD Course
Schibsted Spain - Day 1 - DDD CourseKevin Mas Ruiz
 
Model Driven Architectures
Model Driven ArchitecturesModel Driven Architectures
Model Driven ArchitecturesLalit Kale
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven DesignNETFest
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net coreSam Nasr, MCSA, MVP
 
Domain-Driven Design (Artur Trosin Product Stream)
Domain-Driven Design (Artur Trosin Product Stream)Domain-Driven Design (Artur Trosin Product Stream)
Domain-Driven Design (Artur Trosin Product Stream)IT Arena
 
Done in 60 seconds - Creating Web 2.0 applications made easy
Done in 60 seconds - Creating Web 2.0 applications made easyDone in 60 seconds - Creating Web 2.0 applications made easy
Done in 60 seconds - Creating Web 2.0 applications made easyRoel Hartman
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheelsNaveenkumar Muguda
 
2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use itMark Windholtz
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsMark Windholtz
 
2011 iska - tim m - domain driven design
2011   iska - tim m - domain driven design2011   iska - tim m - domain driven design
2011 iska - tim m - domain driven designTim Mahy
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignFrank Levering
 
Model-driven and low-code development for event-based systems | Bobby Calderw...
Model-driven and low-code development for event-based systems | Bobby Calderw...Model-driven and low-code development for event-based systems | Bobby Calderw...
Model-driven and low-code development for event-based systems | Bobby Calderw...HostedbyConfluent
 

Ähnlich wie An Introduction to Domain Driven Design in PHP (20)

Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design Introduction
Domain Driven Design IntroductionDomain Driven Design Introduction
Domain Driven Design Introduction
 
Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
SDWest2005Goetsch
SDWest2005GoetschSDWest2005Goetsch
SDWest2005Goetsch
 
A Case for Outside-In Design
A Case for Outside-In DesignA Case for Outside-In Design
A Case for Outside-In Design
 
MODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in PracticeMODEL-DRIVEN ENGINEERING (MDE) in Practice
MODEL-DRIVEN ENGINEERING (MDE) in Practice
 
Schibsted Spain - Day 1 - DDD Course
Schibsted Spain - Day 1 - DDD CourseSchibsted Spain - Day 1 - DDD Course
Schibsted Spain - Day 1 - DDD Course
 
Model Driven Architectures
Model Driven ArchitecturesModel Driven Architectures
Model Driven Architectures
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
 
Domain-Driven Design (Artur Trosin Product Stream)
Domain-Driven Design (Artur Trosin Product Stream)Domain-Driven Design (Artur Trosin Product Stream)
Domain-Driven Design (Artur Trosin Product Stream)
 
Ramesh Resume
Ramesh ResumeRamesh Resume
Ramesh Resume
 
Done in 60 seconds - Creating Web 2.0 applications made easy
Done in 60 seconds - Creating Web 2.0 applications made easyDone in 60 seconds - Creating Web 2.0 applications made easy
Done in 60 seconds - Creating Web 2.0 applications made easy
 
Software Development: Beyond Training wheels
Software Development: Beyond Training wheelsSoftware Development: Beyond Training wheels
Software Development: Beyond Training wheels
 
2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it2019-Nov: Domain Driven Design (DDD) and when not to use it
2019-Nov: Domain Driven Design (DDD) and when not to use it
 
Bdd with m spec
Bdd with m specBdd with m spec
Bdd with m spec
 
Domain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic PatternsDomain Driven Design Big Picture Strategic Patterns
Domain Driven Design Big Picture Strategic Patterns
 
2011 iska - tim m - domain driven design
2011   iska - tim m - domain driven design2011   iska - tim m - domain driven design
2011 iska - tim m - domain driven design
 
Code & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven DesignCode & Cannoli - Domain Driven Design
Code & Cannoli - Domain Driven Design
 
Model-driven and low-code development for event-based systems | Bobby Calderw...
Model-driven and low-code development for event-based systems | Bobby Calderw...Model-driven and low-code development for event-based systems | Bobby Calderw...
Model-driven and low-code development for event-based systems | Bobby Calderw...
 

Kürzlich hochgeladen

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Kürzlich hochgeladen (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

An Introduction to Domain Driven Design in PHP

  • 1. An Introduction to Domain Driven Design in PHP Chris Renner Nashville PHP Meetup August 9, 2016
  • 2. Agenda • A bit about me & what I do • Describe our principle application and its purpose • High-level DDD concepts • Implementation strategies and patterns • Lessons learned • Conclusion
  • 3. About Me - Personal • Married 17 years with two little ones (10 and 3) • In Nashville 18 years, originally from Kentucky • Interests: Too many!
  • 5. About Me - Professional • Sr. Application Developer at VUMC, 12 years at Vanderbilt,~10 years as PHP dev • Self-taught developer* • internal-facing enterprise scale apps • Prior: proposal writer, contract negotiator
  • 6. What I do • Application Development • User interaction & support • Business Analysis • Reporting and analytics • Support one enterprise app, a few small apps and a couple of websites
  • 7. Our Main App • PEER • Went online July 2007 • Primary business application of a department of 30 users, with hundreds of other “customers”. • Domain is “Contract Management”
  • 8. What is DDD? • A set of solutions to documenting, solving and managing the complexity of business problems in your code. • A methodology for thinking and talking about solving business problems with code
  • 9. DDD is not… • a TV show on Food Network • anything to do with domain names or DNS • code, but rather principles and practices. • MVC or an MVC replacement. • a design pattern. • an all-or-nothing proposition.
  • 10. DDD is… • a process • modeling business logic in code • a common language among devs and stakeholders • agile*
  • 11. When to use? • Complicated business logic • Large code base • Multiple devs • Long dev cycle, app lifecycle • moving paper/human processes into an electronic system
  • 12. When NOT to use? • Short development cycle • Microservices • Simple business models • Minimal business logic
  • 13. Requirements • General intelligence - must understand client’s business process • Communication skills - must be able to translate biz speak to tech speak and vice versa • Humility
  • 15. Domain • A sphere of knowledge, influence or activity. The subject area to which the user applies a program is the domain of the software • e.g. Used Car Sales, Patient Medical Records, Contract Management* • not Automotive, Health Care
  • 16. Model • A software abstraction representing a specific concept in the domain. • Data & Biz Logic • Will be continually refined as understanding of domain grows.
  • 17. Ubiquitous Language • Ubiquitous: omnipresent, everywhere • Set of terms structured around the domain model and used by both tech and biz team members when discussing the project. • Use in the code
  • 18. Bounded Context • Limits drawn around the scope of the business problem create a context area. • Statements about a model can only be understood within this context.
  • 20. Entities • e.g. Car, Patient, Invoice, Contract • Typically 1-class per entity • Mimic real objects • Data + Business Logic = Domain Models
  • 21. class Widget { public $id; public $price; public function __construct() { } public function isDiscountable() { // logic here } }
  • 22. Factories • Objects that create instances of other objects • TIP: Pass in an ID to get back hydrated instance
  • 23. class Widget { public static function factory($id = null) { // create instance $obj = new Widget(); // hydrate with data from persistence if ($id) { WidgetMapper::hydrate($obj, $id); } return $obj; } } $foo = Widget::factory(1234);
  • 24. Aggregates • One-to-Many • E.g. Entity “Invoice” may have multiple line items, each probably a LineItem Entity • Roll up many like things into a parent
  • 25. Domain Services • Use sparingly! • Capture business logic that operates on more than one entity/model • When a class isn’t a “thing” • != application services
  • 26. Domain Events • Real actions, events or activities in the business • Becomes your domain logic • Place in model/entity or service layer
  • 27. Modules • Separate code into meaningful subject areas based on business logic • One module for system/application support/architectural stuff, then modules for each business sub-area or bundle of related code • Personal preference
  • 28. Layers (Hexagonal Architecture) • Separation of concerns • Outer later is interface, either UI or service connections • middle layer that translates requests into business actions • inner layer is business logic
  • 29. Patterns and Best Practices
  • 30. Domain Models • Implementation of Entity • Use Inheritance and/or Traits & Interfaces to abstract and re-use • Domain Model + Mapper + Table Data Gateway patterns
  • 31. Domain Model Mapper Table • All SQL in Table class • Mapper translates between Model properties and table column • Model has NO awareness of the Table class • Application code (controllers, services) interact with the Model only
  • 32. class Widget extends DomainModelAbstract { public $id; public $name; public $price; protected $department; public static function factory($id = null) { // create instance $obj = new Widget(); // hydrate with data from persistence if ($id) { WidgetMapper::hydrate($obj, $id); } return $obj; } }
  • 33. class WidgetTable extends TableAbstract { public $name = ‘WIDGET_TABLE’; public $primary = ‘ID’; public function fetchById($id) { $sql = “SELECT * FROM $this->name WHERE $this->primary = :id”; $result = $db->query($sql, [‘:id’ = > $id]); return $result->fetch(); } }
  • 34. class WidgetMapper extends MapperAbstract { public static $columns = [ ‘id’ => ‘ID’, ‘name’ => ‘NAME, ‘price’ => ‘PRICE’ ] }
  • 35. Interacting with a Domain Model Instance $myWidget = Widget::factory(); $myWidget->setName(‘Acme Super Thingy’); $myWidget->price = 99.95; $id = $myWidget->save(); echo $id; // 1234
  • 36. Lazy Loading class Widget { public $deptId; private $department; public function getDept() { if (!$this->department) { $this->department = Department::factory($this->deptId); } return $this->department; } } echo $widget->getDept()->name; // Human Resources
  • 37. Getters and Setters • Don’t Overuse! • Opportunity to Add Logic
  • 38. public function setName($string) { $this->name = substr($string, 5, 100); } public function setStatus($status) { if($status != $this->status) { $this->addtoStatusLog($status); } $this->status = $status; }
  • 39. Strategy Pattern • aka “Policy Pattern” • encapsulate business rules/logic
  • 40. Strategy Pattern Example class Contract { public function isExpired() { if(strtotime($this->endDate) < time()) { return true; } return false; } } $contract->setEndDate(‘2016-08-01’); echo $contract->isExpired(); // true
  • 41. Specification Pattern • like Strategy, but a separate class instead of a function • single public function isSatisfiedBy() determines if an object meets specified criteria • can be chained
  • 42. Specification Pattern Example class BillingAgreementSpecification { public function isSatisfiedBy(Contract $contract) { if(!$contract->requirementA) { return false; } if(!$contract->requirementB) { return false; } return true; } } $spec = new BillingAgreementSpecification(); echo $spec->isSatisfiedBy($contract); // true
  • 44. Intention-Revealing Interface • Contextually Relevant Variable, Function and Class Names • public function sendFullyExecutedEmail()
  • 45. Comment Your Code • comment and docblock everything
  • 46. IDs for Everything! • usernames and emails are NOT unique IDs! • give everything an internal numeric ID, even if its never seen by user
  • 47. Minimize Shortcuts • Code it to work first, then go back and make it right • hack-y code will bite you later • iterate + feedback, don’t assume you fully understand the problem - the Model will never be “done”
  • 48. Avoid Framework Lock-In • Preference for components • Composer • Consider extending a Micro-Framework v. an all-in- one package
  • 49. Good OOP required • Abstraction • Encapsulation • Separation of Concerns
  • 50. Avoid Unnecessary Complexity • Ask “is this necessary?” • Don’t let DDD rules become a prison • Simplicity = Maintainability
  • 51. Become the Expert • You will uncover flaws and inefficiencies in the business logic • You may end up understanding the business process better than stakeholders
  • 52. Summary • DDD a way of communicating and thinking about a complex business problem • Implementing DDD involves the best of enterprise design patterns, OOP and clean code principles. • Use what works, every project is different
  • 53. References • Domain Driven Design: Tackling Complexity in the Heart of Software - Eric Evans, 2003 • DDD Reference - Eric Evans, https://www.domainlanguage.com/ddd/reference/ • Clean Code: A Handbook of Agile Software Craftsmanship - Robert Martin, 2008 • Patterns of Enterprise Application Architecture - Martin Fowler, 2002 • phproundtable: Domain Driven Design in PHP - https://www.phproundtable.com/episode/domain-driven-design- in-php
  • 54. Find Me • Twitter: @rennerchris • Web: www.chrisrenner.com • Email: rennercr@gmail.com
  • 55. I’m Troy McClure, and you might remember me from such tech talks as “Creating Legacy Code” and “Maximizing Technical Debt”