Design Patterns
illustrated
010PHP

Törööö
By Laurent Steinmayer

Herman Peeren, February 13, 2014
(Design Patterns illust...
Design Patterns
●●
●●
●●
●●

recipes against common (OO-) programming problems
code reuse: no need to reinvent the wheel
c...
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 segrega...
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...
Classic pattern categories
creational, structural and behavioral patterns:

►►creational: object instantiation
►►structura...
Other categorisations
Loek Bergman (dev. from Rotterdam):
►►transformational
►►transportational
►►translational
Anthony Fe...
Creational design patterns
►►Factory Method: Allow subclasses to “decide” which class
to instantiate.
►►Abstract Factory: ...
Factory Method

Provide an interface for the creation of objects.

©c
yepr

Allow subclasses to “decide” which class to in...
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 factor...
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: doc...
Singleton

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

© yepr
c

Oh, I’m so
loooooo...
Singleton

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

© ...
“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.prototy...
Structural design patterns
●● Adapter: Adapt an interface to an expected interface.
●● Bridge: Decouple an interface from ...
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.)

Instea...
Bridge

Decouple an abstraction from its implementation.

COLA

1 LITER

1 LITER

COLA

1 LITER

1 LITER

COLA

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(
ar...
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.

©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/decoupli...
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 ...
Replace implicit language with Interpreter:
search-methods including combinations:
►►belowPriceAvoidingAColor( )
►►byColor...
Iterator

Enable sequential access to collection elements, without showing

the underlying data-structures (array, list, r...
PHP: SPL iterators
►►http://www.php.net/manual/en/class.iterator.php
►►http://www.php.net/manual/en/spl.iterators.php
Stef...
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.......
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) {
retur...
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

printservic...
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

Kerie...
Resign Patterns:

Ailments of Unsuitable Project-Disoriented Software
Questions?

Contact info:
Herman Peeren
herman@yepr.nl
© Yepr
Design Pattern Illustrations: Nelleke Verhoeff, Red Cheeks F...
Upcoming SlideShare
Loading in …5
×

Design patterns illustrated 010PHP

3,094 views

Published on

All 'classic' 23 GOF Design Patterns, illustrated by Nelleke Verhoeff (Red Cheeks Factory). Trying to show the essence of each Design Pattern, with some examples from PHP.

Second version of my Design Patterns presentation. This presentation was held February 13, 2014 at the 010PHP meeting in Rotterdam. Presentation was in Dutch.

Published in: Technology
  • Some more explanation at those drawings can be found in an article I wrote 4 years ago for Blaise Pascal Magazine: http://www.blaisepascal.eu/index.php?actie=./peeren/page1 (with a few lines in Delphi as example). Language was different, patterns were the same.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Thank you, Randy. These are the drawings we made 4 years ago. There are some that I'm a bit less enthusiastic about now, for instance Bridge. That one is made to tell a story about two kinds of 'trees' (implementation and abstraction), but when you just see the drawing with cola and milk, you won't get that. Also the people gathered around the box to choose a Strategy is not completely self-explanatory. But I got the drawings out of the dust and 'reanimated' them. Very glad with that. The main improvement I did now was getting some more useful examples (like: about payment in a webshop). Many examples of Design Patterns are about subjects you'll never encounter as a developer... Maybe we will make a second version of all drawings and then put them in a book; the plan is to make a book without code and take the organisation of a fictional company as example. Of course the organisation of the company is a metaphore for the organisation of a computerprogram.

    On our monthly 010PHP-meetings I'll now work out some patterns a littel bit more. But then just one on an evening. Refactoring towards State Pattern will be for next month. Doing all 23 on one evening is a bit much. Still looking for some more story to tie them together when I would do that again: except for the first 5 creational patterns, I did them in the alphabetical order they have in the GOF book.

    I was glad to see there is so much interest by other developers for Design Patterns. Good motivation to keep on going with this.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Very good. I thought the illustrations for each pattern were excellent at communicating what that pattern does - and that is not easy with design patterns.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Design patterns illustrated 010PHP

  1. 1. Design Patterns illustrated 010PHP Törööö By Laurent Steinmayer Herman Peeren, February 13, 2014 (Design Patterns illustrations: Nelleke Verhoeff, 2010)
  2. 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. 3. The one constant in software development:
  4. 4. The one constant in software development: CHANGE!
  5. 5. The one constant in software development: CHANGE! I knew it ...
  6. 6. Ideal: code as modular black boxes
  7. 7. Single responsibility principle Open for extension, closed for modification Liskov subsitution principle Interface segregation Dependency inversion
  8. 8. Avoid: tight coupling!
  9. 9. It might get you into trouble...
  10. 10. Beware of: Code smells!
  11. 11. some code smells: ►►duplicate code ►►long method ►►large class ►►combinatorial explosion ►►conditional complexity ►►switch statements ►►indecent exposure
  12. 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. 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. 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. 15. Factory Method Provide an interface for the creation of objects. ©c yepr Allow subclasses to “decide” which class to instantiate.
  16. 16. Example: different kinds of customers...
  17. 17. ...with different kinds of invoices
  18. 18. Abstract Factory ©c yepr Povide an interface for creating families of related or dependent objects. A factory for factories.
  19. 19. Example: a Gold customer, cart, invoice, etc.
  20. 20. Builder ©c yepr Seperate the construction process (how) of a complex object from the concrete representations (what).
  21. 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. 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. 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. 24. “Every advantage has its disadvantages” (free to Johan Cruyff, Dutch Football Pattern Designer and Ajax-fan...)
  25. 25. Prototype Make variations on copies of a basic-object. c © yepr COPY-SERVICE
  26. 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. 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. 28. Adapter (= Wrapper) ©c yepr Adapt an interface to an expected interface.
  29. 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. 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. 31. Example: payment and payment providers
  32. 32. Composite ©c yepr Create a tree structure for part-whole hierarchies. A node is also a (part of a) tree. Recursive:
  33. 33. Decorator ©cyepr Add extra functionallity (at runtime), while keeping the interface the same. Matroushka’s...
  34. 34. Decorator
  35. 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. 36. Facade Provide a general (simpler) interface for a set of interfaces. ©c yepr looks simple
  37. 37. Flyweight ©c yepr Use one instance of a class to provide many “virtual” instances.
  38. 38. Proxy ©c yepr Provide a surrogate or placeholder for another object to control access to it.
  39. 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. 40. Command Encapsulate a command request in an object. ©c yepr YOU,DO YOUR TASK! TASK LIGHT ON TASK LIGHT OFF
  41. 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. 42. Chain of Responsibility © yepr c Define a method of passing a request among a chain of objects.
  43. 43. Interpreter Domain -> (little) language -> grammar -> objects (DSL) ©c yepr HÉ! he means: do this, do that, and after finishing it, go there!
  44. 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. 45. Iterator Enable sequential access to collection elements, without showing the underlying data-structures (array, list, records, etc) next ©c yepr next
  46. 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. 47. Mediator ©c yepr Layer in between: communication via one object.
  48. 48. Memento Save and restore the internal state of an object. ©cyepr ME
  49. 49. Observer Notify “subscribers” of changes. ME ME ©c yepr WHO? NO ME
  50. 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. 51. Strategy When something can be done in several ways, make those ways interchangeable. ©c yepr POSSIBILITIES
  52. 52. Strategy For instance: different payment possibilities at checkout
  53. 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. 54. Template Method ©c yepr The skeleton of an algorithm is fixed, but parts can be filled in differently.
  55. 55. Visitor Make a kind of plugin-possibility for methods: in that way methods can be added in runtime. ©c yepr printservice!
  56. 56. Move Accumulation to Visitor
  57. 57. Some books GOF: 23 “classical” patterns: fun! classic, The Book good start
  58. 58. PHP and Design Patterns PHPexamples Dec. 2013 Simple Febr. 2013 Selection
  59. 59. PEAA & Refactoring Fowler: architectural patterns for enterprise applications Fowler: also known from refactoring Kerievsky: refactoring to patterns
  60. 60. Resign Patterns: Ailments of Unsuitable Project-Disoriented Software
  61. 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

×