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

Design patterns illustrated 010PHP

  • 1.
    Design Patterns illustrated 010PHP Törööö By LaurentSteinmayer Herman Peeren, February 13, 2014 (Design Patterns illustrations: Nelleke Verhoeff, 2010)
  • 2.
    Design Patterns ●● ●● ●● ●● recipes againstcommon (OO-) programming problems code reuse: no need to reinvent the wheel common language GOF: 23 “classical” patterns 四人帮 classic, The Book
  • 3.
    The one constant insoftware development:
  • 4.
    The one constant insoftware development: CHANGE!
  • 5.
    The one constant insoftware development: CHANGE! I knew it ...
  • 6.
    Ideal: code asmodular black boxes
  • 7.
    Single responsibility principle Openfor extension, closed for modification Liskov subsitution principle Interface segregation Dependency inversion
  • 8.
  • 9.
    It might getyou into trouble...
  • 10.
  • 11.
    some code smells: ►►duplicatecode ►►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 ►►FactoryMethod: 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 aninterface for the creation of objects. ©c yepr Allow subclasses to “decide” which class to instantiate.
  • 16.
    Example: different kindsof customers...
  • 17.
  • 18.
    Abstract Factory ©c yepr Povide aninterface for creating families of related or dependent objects. A factory for factories.
  • 19.
    Example: a Goldcustomer, cart, invoice, etc.
  • 20.
    Builder ©c yepr Seperate the constructionprocess (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 classonly has one instance, and provide a global point of access to it. © yepr c Oh, I’m so loooooooonly
  • 23.
    Singleton Ensure a classonly 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 toJohan Cruyff, Dutch Football Pattern Designer and Ajax-fan...)
  • 25.
    Prototype Make variations oncopies 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 Adaptan interface to an expected interface.
  • 29.
    Unify interfaces withAdapter: 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 abstractionfrom its implementation. COLA 1 LITER 1 LITER COLA 1 LITER 1 LITER COLA MILK COLA MILK ©c yepr MILK COLA
  • 31.
    Example: payment andpayment providers
  • 32.
    Composite ©c yepr Create a treestructure 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...
  • 34.
  • 35.
    In PHP youcan 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 instanceof a class to provide many “virtual” instances.
  • 38.
    Proxy ©c yepr Provide a surrogateor 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 commandrequest in an object. ©c yepr YOU,DO YOUR TASK! TASK LIGHT ON TASK LIGHT OFF
  • 41.
    A command isan 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 languagewith 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 accessto 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 StefanFroelich: ►►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 restorethe internal state of an object. ©cyepr ME
  • 49.
    Observer Notify “subscribers” ofchanges. ME ME ©c yepr WHO? NO ME
  • 50.
    State Let an objectshow 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 canbe done in several ways, make those ways interchangeable. ©c yepr POSSIBILITIES
  • 52.
    Strategy For instance: differentpayment possibilities at checkout
  • 53.
    Replace Conditional Logicwith 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 skeletonof an algorithm is fixed, but parts can be filled in differently.
  • 55.
    Visitor Make a kindof plugin-possibility for methods: in that way methods can be added in runtime. ©c yepr printservice!
  • 56.
  • 57.
    Some books GOF: 23“classical” patterns: fun! classic, The Book good start
  • 58.
    PHP and DesignPatterns PHPexamples Dec. 2013 Simple Febr. 2013 Selection
  • 59.
    PEAA & Refactoring Fowler: architecturalpatterns for enterprise applications Fowler: also known from refactoring Kerievsky: refactoring to patterns
  • 60.
    Resign Patterns: Ailments ofUnsuitable 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