SlideShare une entreprise Scribd logo
1  sur  61
Télécharger pour lire hors ligne
Design Patterns
illustrated
010PHP

Törööö
By Laurent Steinmayer

Herman Peeren, February 13, 2014
(Design Patterns illustrations: Nelleke Verhoeff, 2010)
Design Patterns
●●
●●
●●
●●

recipes against common (OO-) programming problems
code reuse: no need to reinvent the wheel
common language
GOF: 23 “classical” patterns

四人帮

classic,
The Book
The one

constant in software development:
The one

constant in software development:

CHANGE!
The one

constant in software development:

CHANGE!
I knew it ...
Ideal: code as modular black boxes
Single responsibility principle
Open for extension, closed for modification
Liskov subsitution principle
Interface segregation
Dependency inversion
Avoid: tight coupling!
It might get you into trouble...
Beware of:

Code
smells!
some code smells:
►►duplicate code
►►long method
►►large class
►►combinatorial explosion
►►conditional complexity
►►switch statements
►►indecent exposure
Classic pattern categories
creational, structural and behavioral patterns:

►►creational: object instantiation
►►structural: larger structures of classes or objects
►►behavioral: interaction and distribution of responsibility
Other categorisations
Loek Bergman (dev. from Rotterdam):
►►transformational
►►transportational
►►translational
Anthony Ferrara:
►►Shim : not necessary (for PHP)
►►decompositional: breaking objects apart
►►compositional: making things simpler by assembling
Creational design patterns
►►Factory Method: Allow subclasses to “decide” which class
to instantiate.
►►Abstract Factory: Encapsulate a set of analo	 gous factories that produce families of objects.
►►Builder: Encapsulate the construction of com	 plex objects from their representation; so, the
	same building process can create various repre	 sentations by specifying only type and content.
►►Singleton:	 Ensure that only a single instance of
	a class exists and provide a single method for
	gaining access to it.
►►Prototype: Create an initialized instance for
	cloning or copying.
Factory Method

Provide an interface for the creation of objects.

©c
yepr

Allow subclasses to “decide” which class to instantiate.
Example: different kinds of customers...
...with different kinds of invoices
Abstract Factory

©c
yepr

Povide an interface for creating families of related
or dependent objects. A factory for factories.
Example: a Gold customer, cart, invoice, etc.
Builder

©c
yepr

Seperate the construction process (how) of a complex object
from the concrete representations (what).
Example: querybuilder:
$qb->select(‘u’)
->from(‘User’, ‘u’)
->where(‘u.id = ?1’)
->orderBy(‘u.name’, ‘ASC’);

Example: documentbuilder (for tree-like structures):
$domtree = new DOMDocument(‘1.0’, ‘UTF-8’);

/

/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement(“xml”);
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentTrack = $domtree->createElement(“track”);
$currentTrack = $xmlRoot->appendChild($currentTrack);
// etc...
Singleton

Ensure a class only has one instance, and provide a global
point of access to it.

© yepr
c

Oh, I’m so
loooooooonly
Singleton

Ensure a class only has one instance, and provide a global
point of access to it.
Did anybody say GLOBAL???

© yepr
c

Oh, I’m so
loooooooonly

B

N
A

E
N

!
D
“Every
advantage
has its
disadvantages”

(free to Johan Cruyff,
Dutch Football Pattern Designer
and Ajax-fan...)
Prototype

Make variations on copies of a basic-object.

c
© yepr

COPY-SERVICE
Javascript:
var Person = function() { // bladibla };
var Customer = function(name) {
this.name = name;
};
Customer.prototype = new Person();

Prototype in PHP:
►►adding properties is easy
►►adding behaviour is less obvious, but...
►►CLOSURES can help here, with some (dirty) tricks
Structural design patterns
●● Adapter: Adapt an interface to an expected interface.
●● Bridge: Decouple an interface from its implementation.
●● Composite: Create a tree structure for part-whole hierarchies.
●● Decorator: Extend functionality dynamically.
●● Facade: Simplify usage by defining a high-level interface.
●● Flyweight: Support fine-grained objects 	 fficiently by sharing.
e
●● Proxy: Represent an object with another object for access control.
Adapter (= Wrapper)

©c
yepr

Adapt an interface to an expected interface.
Unify interfaces with Adapter:
For instance: different payment gateways
(PayPal, iDEAL, Hipay, Moneybookers, etc.)

Instead of different interfaces

refactor to

one preferred interface
and write adapters for the others
Bridge

Decouple an abstraction from its implementation.

COLA

1 LITER

1 LITER

COLA

1 LITER

1 LITER

COLA

MILK
COLA

MILK

©c
yepr

MILK

COLA
Example: payment and payment providers
Composite

©c
yepr

Create a tree structure for part-whole hierarchies.
A node is also a (part of a) tree. Recursive:
Decorator

©cyepr

Add extra functionallity (at runtime),
while keeping the interface the same.
Matroushka’s...
Decorator
In PHP you can use __call to copy parent methods:
public function __call($method, $args) {
return call_user_func_array(
array($this->decoratedInstance, $method),
$args
);
}

N.B.: Magic functions are magic...
but come at a cost!
Facade

Provide a general (simpler) interface for a set of interfaces.

©c
yepr

looks
simple
Flyweight

©c
yepr

Use one instance of a class
to provide many “virtual” instances.
Proxy

©c
yepr

Provide a surrogate or placeholder for another object
to control access to it.
Behavioral design patterns
●● Chain of Responsibility: Define a method of passing a

request among a chain of objects.
●● Command: Encapsulate a command request in an object.
●● Interpreter: Allow inclusion of language elements in an application.
●● Iterator: Enable sequential access to collection elements.
●● Mediator: Define simplified communication between classes.
●● Memento: Save and restore the internal state of an object.
●● Observer: Define a scheme for notifying objects of changes to
another object.
●● State: Alter the behavior of an object when its state changes.
●● Strategy: Encapsulate an algorithm inside a class.
●● Template Method: Allow subclasses to redefine the steps of
an algorithm.
●● Visitor: Define a new operation on a class without changing it.
Command

Encapsulate a command request in an object.

©c
yepr

YOU,DO YOUR
TASK!

TASK
LIGHT
ON

TASK
LIGHT
OFF
A command is an object to execute 1 method
Decoupling (Symfony2) Forms from Entities:

http://verraes.net/2013/04/decoupling-symfony2-forms-from-entities/

Chain of Command: Chain of Responsability with Commands

Replace Conditional Dispatcher with Command
if ($actionName == NEW_WORKSHOP) {
//do a lot
} else if ($actionName == ALL_WORKSHOPS) {
// do a lot of other things
} // and many more elseif-statements

NewWorkshopHandler, AllWorkshopsHandler, etc.
Chain of Responsibility
© yepr
c

Define a method of passing a request among a chain of objects.
Interpreter

Domain -> (little) language -> grammar -> objects (DSL)

©c
yepr

HÉ!

he means:
do this, do that,
and after finishing it,
go there!
Replace implicit language with Interpreter:
search-methods including combinations:
►►belowPriceAvoidingAColor( )
►►byColorAndBelowPrice( )
►►byColorSizeAndBelowPrice( )
interpretable expression:
$productSpec =
new AndSpec(
new BelowPriceSpec(9.00),
new NotSpec(newColorSpec(WHITE))
);
“You don’t need an Interpreter for complex languages
or for really simple ones.” (Joshua Kerievsky)
Iterator

Enable sequential access to collection elements, without showing

the underlying data-structures (array, list, records, etc)

next

©c
yepr

next
PHP: SPL iterators
►►http://www.php.net/manual/en/class.iterator.php
►►http://www.php.net/manual/en/spl.iterators.php
Stefan Froelich:
►►http://www.sitepoint.com/using-spl-iterators-1/
►►http://www.sitepoint.com/using-spl-iterators-2/
Anthony Ferrara video:
►►http://blog.ircmaxell.com/2013/01/todays-programming-with-anthony-video.html
Mediator

©c
yepr

Layer in between: communication via one object.
Memento

Save and restore the internal state of an object.

©cyepr

ME
Observer

Notify “subscribers” of changes.

ME
ME

©c
yepr

WHO?

NO

ME
State

Let an object show other methods
after a change of internal state (as if it changes it’s class).

in a.....hick......different state,
....hick....I behave differently....hick.....

©c
yepr
Strategy

When something can be done in several ways, make those
ways interchangeable.

©c
yepr

POSSIBILITIES
Strategy

For instance: different payment possibilities at checkout
Replace Conditional Logic with Strategy
if ($income >= 10000) {
return $income*0.365;
} else if ($income <= 30000) {
return ($income-10000)*0.2+35600;
} else //etc (...)
return ($income-60000)*0.02+105600;
} // note: mutual exclusive grouping
if ($income <= 100000) {
$strategy = new InsuranceStrategyLow($income);
} else if ($income <= 300000) {
$strategy = new InsuranceStrategyMedium($income);
} else //etc (...)
$strategy = new InsuranceStrategyVeryHigh($income);
}
return $strategy->calculateInsurance();
http://wiki.jetbrains.net/intellij/Replace_conditional_logic_with_strategy_pattern
Template Method

©c
yepr

The skeleton of an algorithm is fixed,
but parts can be filled in differently.
Visitor

Make a kind of plugin-possibility for methods:
in that way methods can be added in runtime.

©c
yepr

printservice!
Move Accumulation to Visitor
Some books
GOF: 23 “classical” patterns:

fun!
classic,
The Book

good start
PHP and Design Patterns
PHPexamples

Dec. 2013
Simple

Febr.
2013
Selection
PEAA & Refactoring

Fowler:
architectural patterns
for
enterprise applications

Fowler: also
known from
refactoring

Kerievsky:
refactoring
to patterns
Resign Patterns:

Ailments of Unsuitable Project-Disoriented Software
Questions?

Contact info:
Herman Peeren
herman@yepr.nl
© Yepr
Design Pattern Illustrations: Nelleke Verhoeff, Red Cheeks Factory, 2010
Creative Commons Public License for noncommercial use
http://creativecommons.org/licenses/by-nc/3.0/legalcode

Contenu connexe

Tendances

OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVPHarshith Keni
 
Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtimeInferis
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS ImplimentationUsman Mehmood
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 

Tendances (20)

OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtime
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Objective c
Objective cObjective c
Objective c
 
Python advance
Python advancePython advance
Python advance
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
core java
core javacore java
core java
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 

Similaire à Design patterns illustrated 010PHP

WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin LocalizationRonald Huereca
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.pptrani marri
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and ScalaFilip Krikava
 
Java for android developers
Java for android developersJava for android developers
Java for android developersAly Abdelkareem
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 

Similaire à Design patterns illustrated 010PHP (20)

WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin Localization
 
OOP
OOPOOP
OOP
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Effective PHP. Part 2
Effective PHP. Part 2Effective PHP. Part 2
Effective PHP. Part 2
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Domain specific languages and Scala
Domain specific languages and ScalaDomain specific languages and Scala
Domain specific languages and Scala
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 

Plus de Herman Peeren

ProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdfProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdfHerman Peeren
 
ExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdfExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdfHerman Peeren
 
Programmeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereldProgrammeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereldHerman Peeren
 
Improve our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional ProgrammingImprove our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional ProgrammingHerman Peeren
 
DCI DDD-BE April 2015
DCI DDD-BE April 2015DCI DDD-BE April 2015
DCI DDD-BE April 2015Herman Peeren
 
Next Generation Joomla!
Next Generation Joomla!Next Generation Joomla!
Next Generation Joomla!Herman Peeren
 
Behat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHPBehat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHPHerman Peeren
 
Print, geen kunst aan
Print, geen kunst aanPrint, geen kunst aan
Print, geen kunst aanHerman Peeren
 
Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Herman Peeren
 
#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensies#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensiesHerman Peeren
 
Jug010 120320-templates
Jug010 120320-templatesJug010 120320-templates
Jug010 120320-templatesHerman Peeren
 
Joomla2.0 architecture
Joomla2.0 architectureJoomla2.0 architecture
Joomla2.0 architectureHerman Peeren
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Herman Peeren
 
Commercial gpljoomla
Commercial gpljoomlaCommercial gpljoomla
Commercial gpljoomlaHerman Peeren
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns IllustratedHerman Peeren
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!Herman Peeren
 

Plus de Herman Peeren (20)

ProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdfProjectionalForms-2023-11-14.pdf
ProjectionalForms-2023-11-14.pdf
 
ExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdfExtensionGenerator-JoomlaDagen2023-slides.pdf
ExtensionGenerator-JoomlaDagen2023-slides.pdf
 
Cut & Shave
Cut & ShaveCut & Shave
Cut & Shave
 
Programmeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereldProgrammeren, talen en het begrijpen van de wereld
Programmeren, talen en het begrijpen van de wereld
 
Dci in PHP
Dci in PHPDci in PHP
Dci in PHP
 
Improve our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional ProgrammingImprove our PHP code with ideas from Functional Programming
Improve our PHP code with ideas from Functional Programming
 
DCI DDD-BE April 2015
DCI DDD-BE April 2015DCI DDD-BE April 2015
DCI DDD-BE April 2015
 
Event Sourcing
Event SourcingEvent Sourcing
Event Sourcing
 
Next Generation Joomla!
Next Generation Joomla!Next Generation Joomla!
Next Generation Joomla!
 
Behat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHPBehat, Behavioral Driven Development (BDD) in PHP
Behat, Behavioral Driven Development (BDD) in PHP
 
Print, geen kunst aan
Print, geen kunst aanPrint, geen kunst aan
Print, geen kunst aan
 
Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!Jooctrine - Doctrine ORM in Joomla!
Jooctrine - Doctrine ORM in Joomla!
 
#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensies#jd12nl Joomla 2.5 extensies
#jd12nl Joomla 2.5 extensies
 
#jd12nl Seblod 2
#jd12nl  Seblod 2#jd12nl  Seblod 2
#jd12nl Seblod 2
 
Jug010 120320-templates
Jug010 120320-templatesJug010 120320-templates
Jug010 120320-templates
 
Joomla2.0 architecture
Joomla2.0 architectureJoomla2.0 architecture
Joomla2.0 architecture
 
Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.Webservices: connecting Joomla! with other programs.
Webservices: connecting Joomla! with other programs.
 
Commercial gpljoomla
Commercial gpljoomlaCommercial gpljoomla
Commercial gpljoomla
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!
 

Dernier

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Dernier (20)

Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

Design patterns illustrated 010PHP

  • 1. Design Patterns illustrated 010PHP Törööö By Laurent Steinmayer Herman Peeren, February 13, 2014 (Design Patterns illustrations: Nelleke Verhoeff, 2010)
  • 2. Design Patterns ●● ●● ●● ●● recipes against common (OO-) programming problems code reuse: no need to reinvent the wheel common language GOF: 23 “classical” patterns 四人帮 classic, The Book
  • 3. The one constant in software development:
  • 4. The one constant in software development: CHANGE!
  • 5. The one constant in software development: CHANGE! I knew it ...
  • 6. Ideal: code as modular black boxes
  • 7. Single responsibility principle Open for extension, closed for modification Liskov subsitution principle Interface segregation Dependency inversion
  • 9. It might get you into trouble...
  • 11. some code smells: ►►duplicate code ►►long method ►►large class ►►combinatorial explosion ►►conditional complexity ►►switch statements ►►indecent exposure
  • 12. Classic pattern categories creational, structural and behavioral patterns: ►►creational: object instantiation ►►structural: larger structures of classes or objects ►►behavioral: interaction and distribution of responsibility
  • 13. Other categorisations Loek Bergman (dev. from Rotterdam): ►►transformational ►►transportational ►►translational Anthony Ferrara: ►►Shim : not necessary (for PHP) ►►decompositional: breaking objects apart ►►compositional: making things simpler by assembling
  • 14. Creational design patterns ►►Factory Method: Allow subclasses to “decide” which class to instantiate. ►►Abstract Factory: Encapsulate a set of analo gous factories that produce families of objects. ►►Builder: Encapsulate the construction of com plex objects from their representation; so, the same building process can create various repre sentations by specifying only type and content. ►►Singleton: Ensure that only a single instance of a class exists and provide a single method for gaining access to it. ►►Prototype: Create an initialized instance for cloning or copying.
  • 15. Factory Method Provide an interface for the creation of objects. ©c yepr Allow subclasses to “decide” which class to instantiate.
  • 16. Example: different kinds of customers...
  • 17. ...with different kinds of invoices
  • 18. Abstract Factory ©c yepr Povide an interface for creating families of related or dependent objects. A factory for factories.
  • 19. Example: a Gold customer, cart, invoice, etc.
  • 20. Builder ©c yepr Seperate the construction process (how) of a complex object from the concrete representations (what).
  • 21. Example: querybuilder: $qb->select(‘u’) ->from(‘User’, ‘u’) ->where(‘u.id = ?1’) ->orderBy(‘u.name’, ‘ASC’); Example: documentbuilder (for tree-like structures): $domtree = new DOMDocument(‘1.0’, ‘UTF-8’); / /* create the root element of the xml tree */ $xmlRoot = $domtree->createElement(“xml”); /* append it to the document created */ $xmlRoot = $domtree->appendChild($xmlRoot); $currentTrack = $domtree->createElement(“track”); $currentTrack = $xmlRoot->appendChild($currentTrack); // etc...
  • 22. Singleton Ensure a class only has one instance, and provide a global point of access to it. © yepr c Oh, I’m so loooooooonly
  • 23. Singleton Ensure a class only has one instance, and provide a global point of access to it. Did anybody say GLOBAL??? © yepr c Oh, I’m so loooooooonly B N A E N ! D
  • 24. “Every advantage has its disadvantages” (free to Johan Cruyff, Dutch Football Pattern Designer and Ajax-fan...)
  • 25. Prototype Make variations on copies of a basic-object. c © yepr COPY-SERVICE
  • 26. Javascript: var Person = function() { // bladibla }; var Customer = function(name) { this.name = name; }; Customer.prototype = new Person(); Prototype in PHP: ►►adding properties is easy ►►adding behaviour is less obvious, but... ►►CLOSURES can help here, with some (dirty) tricks
  • 27. Structural design patterns ●● Adapter: Adapt an interface to an expected interface. ●● Bridge: Decouple an interface from its implementation. ●● Composite: Create a tree structure for part-whole hierarchies. ●● Decorator: Extend functionality dynamically. ●● Facade: Simplify usage by defining a high-level interface. ●● Flyweight: Support fine-grained objects fficiently by sharing. e ●● Proxy: Represent an object with another object for access control.
  • 28. Adapter (= Wrapper) ©c yepr Adapt an interface to an expected interface.
  • 29. Unify interfaces with Adapter: For instance: different payment gateways (PayPal, iDEAL, Hipay, Moneybookers, etc.) Instead of different interfaces refactor to one preferred interface and write adapters for the others
  • 30. Bridge Decouple an abstraction from its implementation. COLA 1 LITER 1 LITER COLA 1 LITER 1 LITER COLA MILK COLA MILK ©c yepr MILK COLA
  • 31. Example: payment and payment providers
  • 32. Composite ©c yepr Create a tree structure for part-whole hierarchies. A node is also a (part of a) tree. Recursive:
  • 33. Decorator ©cyepr Add extra functionallity (at runtime), while keeping the interface the same. Matroushka’s...
  • 35. In PHP you can use __call to copy parent methods: public function __call($method, $args) { return call_user_func_array( array($this->decoratedInstance, $method), $args ); } N.B.: Magic functions are magic... but come at a cost!
  • 36. Facade Provide a general (simpler) interface for a set of interfaces. ©c yepr looks simple
  • 37. Flyweight ©c yepr Use one instance of a class to provide many “virtual” instances.
  • 38. Proxy ©c yepr Provide a surrogate or placeholder for another object to control access to it.
  • 39. Behavioral design patterns ●● Chain of Responsibility: Define a method of passing a request among a chain of objects. ●● Command: Encapsulate a command request in an object. ●● Interpreter: Allow inclusion of language elements in an application. ●● Iterator: Enable sequential access to collection elements. ●● Mediator: Define simplified communication between classes. ●● Memento: Save and restore the internal state of an object. ●● Observer: Define a scheme for notifying objects of changes to another object. ●● State: Alter the behavior of an object when its state changes. ●● Strategy: Encapsulate an algorithm inside a class. ●● Template Method: Allow subclasses to redefine the steps of an algorithm. ●● Visitor: Define a new operation on a class without changing it.
  • 40. Command Encapsulate a command request in an object. ©c yepr YOU,DO YOUR TASK! TASK LIGHT ON TASK LIGHT OFF
  • 41. A command is an object to execute 1 method Decoupling (Symfony2) Forms from Entities: http://verraes.net/2013/04/decoupling-symfony2-forms-from-entities/ Chain of Command: Chain of Responsability with Commands Replace Conditional Dispatcher with Command if ($actionName == NEW_WORKSHOP) { //do a lot } else if ($actionName == ALL_WORKSHOPS) { // do a lot of other things } // and many more elseif-statements NewWorkshopHandler, AllWorkshopsHandler, etc.
  • 42. Chain of Responsibility © yepr c Define a method of passing a request among a chain of objects.
  • 43. Interpreter Domain -> (little) language -> grammar -> objects (DSL) ©c yepr HÉ! he means: do this, do that, and after finishing it, go there!
  • 44. Replace implicit language with Interpreter: search-methods including combinations: ►►belowPriceAvoidingAColor( ) ►►byColorAndBelowPrice( ) ►►byColorSizeAndBelowPrice( ) interpretable expression: $productSpec = new AndSpec( new BelowPriceSpec(9.00), new NotSpec(newColorSpec(WHITE)) ); “You don’t need an Interpreter for complex languages or for really simple ones.” (Joshua Kerievsky)
  • 45. Iterator Enable sequential access to collection elements, without showing the underlying data-structures (array, list, records, etc) next ©c yepr next
  • 46. PHP: SPL iterators ►►http://www.php.net/manual/en/class.iterator.php ►►http://www.php.net/manual/en/spl.iterators.php Stefan Froelich: ►►http://www.sitepoint.com/using-spl-iterators-1/ ►►http://www.sitepoint.com/using-spl-iterators-2/ Anthony Ferrara video: ►►http://blog.ircmaxell.com/2013/01/todays-programming-with-anthony-video.html
  • 47. Mediator ©c yepr Layer in between: communication via one object.
  • 48. Memento Save and restore the internal state of an object. ©cyepr ME
  • 49. Observer Notify “subscribers” of changes. ME ME ©c yepr WHO? NO ME
  • 50. State Let an object show other methods after a change of internal state (as if it changes it’s class). in a.....hick......different state, ....hick....I behave differently....hick..... ©c yepr
  • 51. Strategy When something can be done in several ways, make those ways interchangeable. ©c yepr POSSIBILITIES
  • 52. Strategy For instance: different payment possibilities at checkout
  • 53. Replace Conditional Logic with Strategy if ($income >= 10000) { return $income*0.365; } else if ($income <= 30000) { return ($income-10000)*0.2+35600; } else //etc (...) return ($income-60000)*0.02+105600; } // note: mutual exclusive grouping if ($income <= 100000) { $strategy = new InsuranceStrategyLow($income); } else if ($income <= 300000) { $strategy = new InsuranceStrategyMedium($income); } else //etc (...) $strategy = new InsuranceStrategyVeryHigh($income); } return $strategy->calculateInsurance(); http://wiki.jetbrains.net/intellij/Replace_conditional_logic_with_strategy_pattern
  • 54. Template Method ©c yepr The skeleton of an algorithm is fixed, but parts can be filled in differently.
  • 55. Visitor Make a kind of plugin-possibility for methods: in that way methods can be added in runtime. ©c yepr printservice!
  • 57. Some books GOF: 23 “classical” patterns: fun! classic, The Book good start
  • 58. PHP and Design Patterns PHPexamples Dec. 2013 Simple Febr. 2013 Selection
  • 59. PEAA & Refactoring Fowler: architectural patterns for enterprise applications Fowler: also known from refactoring Kerievsky: refactoring to patterns
  • 60. Resign Patterns: Ailments of Unsuitable Project-Disoriented Software
  • 61. Questions? Contact info: Herman Peeren herman@yepr.nl © Yepr Design Pattern Illustrations: Nelleke Verhoeff, Red Cheeks Factory, 2010 Creative Commons Public License for noncommercial use http://creativecommons.org/licenses/by-nc/3.0/legalcode