SlideShare a Scribd company logo
Design pattern in PHP


   Filippo De Santis - fd@ideato.it - @filippodesantis
Design pattern in PHP

               Web developer

        Working in @ideato since 2009

             XP and Kanban user
Design pattern in PHP
     What is a design pattern?
Design pattern in PHP
                What is a design pattern?

“Each pattern describes a problem which occurs over and
over again in our environment, and then describes the core
of the solution to that problem, in such a way that you can
 use this solution a million times over, without ever doing it
                    the same way twice”

                                       Christopher Alexander
Design pattern in PHP
                What is a design pattern?


“A pattern is a [general] solution to a problem in a context”

                                                Gang of four
Design pattern in PHP
             Elements of a design pattern



                       Name

Used to describe a design problem, its solution and its
          consequences in a word or two
Design pattern in PHP
     Elements of a design pattern



              Problem

   Describes when to apply a pattern
Design pattern in PHP
            Elements of a design pattern



                     Solution

Describes the elements that make up the design, their
  relationships, responsibilities, and collaborations
Design pattern in PHP
          Elements of a design pattern



               Consequences

The results and trade-offs of applying the pattern
Design pattern in PHP
        Singleton
Design pattern in PHP
                  Singleton



  Ensures that a class has one instance only
    Provides a global point of access to it
Design pattern in PHP
          Singleton



       Access control
      Only one instance


          YES!
Design pattern in PHP
                       Singleton

       Used to replace global variables
      [changing the name does not change the problem]

  Violates the Single Responsibility Principle
          [creation + singleton class functionality]




                         NO!
Design pattern in PHP
              Singleton



 private function __construct() {}
Design pattern in PHP
              Singleton



  private static $instance = false;
Design pattern in PHP
                Singleton


public static function getInstance() {
  if (false == self::$instance) {
      self::$instance = new self();
  }

    return self::$instance;
}
Design pattern in PHP
                  Singleton
   class Singleton {

       private static $instance = false;

       private function __construct() {}

       public static function getInstance() {
         if (false == self::$instance) {
             self::$instance = new self();
         }

           return self::$instance;
       }
   }

   $instance = Singleton::getInstance();
Design pattern in PHP
       Factory method
Design pattern in PHP
                  Factory method



  Classes delegate responsibility of building objets
Localize the knowledge of which class is the delegate
Design pattern in PHP
           Factory method



    PHP most used implementation:
     Parameterized factory method
Design pattern in PHP
                Factory method


class Factory {

    public function build($condition) {...}

}
Design pattern in PHP
        Factory method




    interface Document {
      ...
    }
Design pattern in PHP
            Factory method


MyDoc implements Document {...}

   YourDoc implements Document {...}

 TheirDoc implements Document {...}
Design pattern in PHP
                Factory method


class Factory {

    /* @return Document */
    public function build($condition) {...}

}
Design pattern in PHP
                    Factory method
class DocumentReaderFactory {
  public function build($type) {
    switch ($type) {
      case 'txt':
        return new TxtReader();
      case 'doc':
        return new DocReader();
      //...
    }
  }
}

foreach ($documents as $document) {
  $factory = new DocumentReaderFactory();
  $reader = $factory->build($document->getType());
  $reader->read($document);
}
Design pattern in PHP
        Adapter
Design pattern in PHP
                       Adapter



Converts the interface of a class into another interface
Design pattern in PHP
                        Adapter




An existing class interface does not match what you need

               To create a reusable class
Design pattern in PHP
             Adapter



  interface AdapterInterface {
    ...
  }
Design pattern in PHP
                       Adapter
                    by class inheritance




Adapter exteds Adaptee implements AdapterInterface {
  ...
}
Design pattern in PHP
                        Adapter
                   by objects composition



Adapter implements AdapterInterface {

    public function __construct(Adaptee $adaptee){
      $this->adaptee = $adaptee;
    }

    ...
}
Design pattern in PHP
                  Adapter



   interface FileOperationsInterface {

       public function getContent($filename);

       public function putContent($filename, $data);

       public function removeFile($filename);

   }
Design pattern in PHP
                  Adapter
                                                   by class inheritance

 class FTPFileAdapter extends FTPFileRepository
                      implements FileOperationsInterface {

     public function getContent($filename) {
     …
     }
     public function putContent($local_file, $data) {
     …
     }
     public function removeFile($filename) {
     …
     }
 }
Design pattern in PHP
                            Adapter
class FTPFileAdapter implements FileOperationsInterface {
                                                                   by objects composition
    public function __construct(FTPFileRepository $repository) {
      $this->repository = $repository;
    }

    public function getContent($filename) {
      $this->repository->download($local_file, $filename);
      return file_get_content($local_file);
    }

    public function putContent($local_file, $data) {
      file_put_contents($local_file, $data);
      $this->repository->upload($remote_file, $local_file);
    }

    public function removeFile($filename){
      $this->repository->remove($filename);
    }
}
Design pattern in PHP
      Template method
Design pattern in PHP
                 Template method



Defines the skeleton of an algorithm in an operation,
        deferring some steps to subclasses
Design pattern in PHP
                 Template method


Implements the invariant parts of an algorithm once
Leaves it up to subclasses the behavior that can vary

  Common behavior localized in a common class

         To control subclasses extensions
Design pattern in PHP
               Template method


Classes implementing a template method should:

      specify hooks (may be overridden)

specify abstract operations (must be overridden)
Design pattern in PHP
            Template method


 abstract operations (must be overridden)

            ie: use prefix “DO”
                  DoRead()
                 DoWrite()
                DoSomething()
Design pattern in PHP
                  Template method

  abstract class Reader {

   abstract protected function openFile($filename);
   abstract protected function readFile();
   abstract protected function closeFile();

   public function readFileAlgorithm($filename) {
    $this->openFile($filename);
    $content = $this->readFile();
    $this->closeFile();

       return $content
   }
Design pattern in PHPmethod
                  Template


  class XMLReader extends Reader {

      protected function openFile($filename) {
        $this->xml = simplexml_load_file($filename);
      }

      protected function readFile() {
        return $this->xml->description;
      }

      public function closeFile(){}

  }
Design pattern in PHPmethod
                  Template

  class CSVReader extends Reader {

   protected function openFile($filename) {
     $this->handle = fopen($filename, "r");
   }

   protected function closeFile() {
     fclose($this->handle);
   }

     protected function readFile() {
       $data = fgetcsv($this->handle);
  	

 return $data[3]; //description
     }
  }
Design pattern in PHPmethod
                  Template
                                           Hooks


     class Parent {
       protected function hook() {}

         public function doSomething() {
           //...
           $this->hook();
         }
     }
Design pattern in PHPmethod
                  Template
                                                        Hooks



  class Child extends Parent {

      protected function hook() {
        //My logic to add into the doSomething method
      }

  }
Design pattern in PHP
      Dependency Injection
Design pattern in PHP
              Dependency Injection



Components are given their dependencies through
their constructors, methods, or directly into fields
Design pattern in PHP
            Dependency Injection



Those components do not get their dependencies
    themselves, or instantiate them directly
Design pattern in PHP
                  Dependency
                                          Injection


    class A {

        public function doSomething() {
          $b = new B();
          //...
        }
    }
                                     NO!
Design pattern in PHP
                  Dependency
                                           Injection


   class A {

       public function construct(B $b) {
         $this->b = $b;
       }

       //...
   }
                                      YES!
Design pattern in PHP
                  Dependency
                                       Injection


   class A {

       public function setB(B $b) {
         $this->b = $b;
       }

       //...
   }
                                      YES!
Design pattern in PHP
                  Dependency
                       Injection

   class A {

       public $b;

       //...
   }

   $a = new A();
   $a->b = new B();
                      YES!
Design pattern in PHP
                  Dependency
                                      Injection
   class A implements DiInterface{
   }

   interface DiInterface {

       public function setB(B $b);

   }


                                     YES!
Design pattern in PHP

             Dependency Injection Container
Dependency                 &
 Injection        Inversion of control
References
    Design Patterns: Elements of Reusable Object-Oriented Software
                E. Gamma, R. Helm, R. Johnson, J.Vlissides
                         Addison-Wesley 1974


 Martin Fowler - http://martinfowler.com/bliki/InversionOfControl.html


  PicoContainer Documentation: http://picocontainer.org/injection.html


SourceMaking - Design Patterns: http://sourcemaking.com/design_patterns


   PHP best practices - Pattern in PHP: http://www.phpbestpractices.it
Thank you!


Filippo De Santis - fd@ideato.it - @filippodesantis

More Related Content

What's hot (20)

PPT
Oops in PHP By Nyros Developer
Nyros Technologies
 
PDF
php_tizag_tutorial
tutorialsruby
 
PDF
Php tutorial
Mohammed Ilyas
 
PPS
Coding Best Practices
mh_azad
 
PDF
PHP Annotations: They exist! - JetBrains Webinar
Rafael Dohms
 
PDF
Introduction to web programming with JavaScript
T11 Sessions
 
PDF
Dart Workshop
Dmitry Buzdin
 
PDF
Code generating beans in Java
Stephen Colebourne
 
PDF
More about PHP
Jonathan Francis Roscoe
 
PDF
Presentation
pnathan_logos
 
PDF
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
PDF
Java SE 8 best practices
Stephen Colebourne
 
PPTX
pebble - Building apps on pebble
Aniruddha Chakrabarti
 
PPTX
Php introduction and configuration
Vijay Kumar Verma
 
PDF
TDD with PhpSpec
CiaranMcNulty
 
PDF
Introduction to php
KIRAN KUMAR SILIVERI
 
PDF
SOLID Principles
Yi-Huan Chan
 
PDF
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
PDF
Project Automation
elliando dias
 
Oops in PHP By Nyros Developer
Nyros Technologies
 
php_tizag_tutorial
tutorialsruby
 
Php tutorial
Mohammed Ilyas
 
Coding Best Practices
mh_azad
 
PHP Annotations: They exist! - JetBrains Webinar
Rafael Dohms
 
Introduction to web programming with JavaScript
T11 Sessions
 
Dart Workshop
Dmitry Buzdin
 
Code generating beans in Java
Stephen Colebourne
 
More about PHP
Jonathan Francis Roscoe
 
Presentation
pnathan_logos
 
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
Java SE 8 best practices
Stephen Colebourne
 
pebble - Building apps on pebble
Aniruddha Chakrabarti
 
Php introduction and configuration
Vijay Kumar Verma
 
TDD with PhpSpec
CiaranMcNulty
 
Introduction to php
KIRAN KUMAR SILIVERI
 
SOLID Principles
Yi-Huan Chan
 
Java 8 best practices - Stephen Colebourne
JAXLondon_Conference
 
Project Automation
elliando dias
 

Viewers also liked (20)

PDF
Xkanban V3: eXtreme Programming, Kanban and Timboxing
Filippo De Santis
 
PPT
Vsena.Foss.Migration.Guide.V1.01
vsena
 
PDF
Intro to Publishing iOS Apps - Full Cycle
Dynamit
 
PPTX
AméRica En El Mundo
Isa Espinoza
 
PPTX
VEKO digital marketing 12 2010
Antti Leino
 
PDF
xkanban v2 (ALE Bathtub III)
Filippo De Santis
 
PPT
VEKO13 Joulu 2009
Antti Leino
 
PPTX
Easy Notes V1.0 En
FrankSchoeneberg
 
PDF
Symfony2: the world slowest framework
Filippo De Santis
 
KEY
Building a-self-sufficient-team
Filippo De Santis
 
KEY
Applied linear algebra
rch850 -
 
PDF
Sosiaalinen media: yhteisöt, sisältö & keskustelut
Antti Leino
 
PDF
Sosiaalinen media työnhaussa
Antti Leino
 
POT
Medical Microbiology Lab
mohammad shenagari
 
PDF
5 Digital Trends for 2013 - Dynamit
Dynamit
 
PDF
Mémoire Estonie
Nicolas Doisy
 
PPS
Youarealwaysonmymind
guest2e7d1e7
 
PDF
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempi
Filippo De Santis
 
PPTX
Suggestions and Ideas for DigitalOcean
Kaan Caliskan
 
PPT
Arquitectura I Escultura Grega
guestd4825b
 
Xkanban V3: eXtreme Programming, Kanban and Timboxing
Filippo De Santis
 
Vsena.Foss.Migration.Guide.V1.01
vsena
 
Intro to Publishing iOS Apps - Full Cycle
Dynamit
 
AméRica En El Mundo
Isa Espinoza
 
VEKO digital marketing 12 2010
Antti Leino
 
xkanban v2 (ALE Bathtub III)
Filippo De Santis
 
VEKO13 Joulu 2009
Antti Leino
 
Easy Notes V1.0 En
FrankSchoeneberg
 
Symfony2: the world slowest framework
Filippo De Santis
 
Building a-self-sufficient-team
Filippo De Santis
 
Applied linear algebra
rch850 -
 
Sosiaalinen media: yhteisöt, sisältö & keskustelut
Antti Leino
 
Sosiaalinen media työnhaussa
Antti Leino
 
Medical Microbiology Lab
mohammad shenagari
 
5 Digital Trends for 2013 - Dynamit
Dynamit
 
Mémoire Estonie
Nicolas Doisy
 
Youarealwaysonmymind
guest2e7d1e7
 
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempi
Filippo De Santis
 
Suggestions and Ideas for DigitalOcean
Kaan Caliskan
 
Arquitectura I Escultura Grega
guestd4825b
 
Ad

Similar to Design attern in php (20)

PDF
OOP in PHP
Tarek Mahmud Apu
 
PPT
OOP
thinkphp
 
PDF
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
PDF
The state of DI - DPC12
Stephan Hochdörfer
 
ZIP
Object Oriented PHP5
Jason Austin
 
PDF
Dependency injection in Drupal 8
Alexei Gorobets
 
PDF
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
PPT
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
PPTX
PHP in one presentation
Milad Rahimi
 
PDF
Phpspec tips&tricks
Filip Golonka
 
PDF
DDD on example of Symfony (Webcamp Odessa 2014)
Oleg Zinchenko
 
PDF
Objects, Testing, and Responsibility
machuga
 
PDF
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
PDF
Multilingualism makes better programmers
Alexander Varwijk
 
PPTX
Ch8(oop)
Chhom Karath
 
PDF
Design patterns revisited with PHP 5.3
Fabien Potencier
 
PPT
Reflection-In-PHP
Mindfire Solutions
 
PDF
Demystifying Object-Oriented Programming - Lone Star PHP
Alena Holligan
 
PDF
Giới thiệu PHP 7
ZendVN
 
PPT
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
OOP in PHP
Tarek Mahmud Apu
 
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
The state of DI - DPC12
Stephan Hochdörfer
 
Object Oriented PHP5
Jason Austin
 
Dependency injection in Drupal 8
Alexei Gorobets
 
Demystifying Object-Oriented Programming - ZendCon 2016
Alena Holligan
 
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
PHP in one presentation
Milad Rahimi
 
Phpspec tips&tricks
Filip Golonka
 
DDD on example of Symfony (Webcamp Odessa 2014)
Oleg Zinchenko
 
Objects, Testing, and Responsibility
machuga
 
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
Multilingualism makes better programmers
Alexander Varwijk
 
Ch8(oop)
Chhom Karath
 
Design patterns revisited with PHP 5.3
Fabien Potencier
 
Reflection-In-PHP
Mindfire Solutions
 
Demystifying Object-Oriented Programming - Lone Star PHP
Alena Holligan
 
Giới thiệu PHP 7
ZendVN
 
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
Ad

Recently uploaded (20)

PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
July Patch Tuesday
Ivanti
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
July Patch Tuesday
Ivanti
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 

Design attern in php

  • 1. Design pattern in PHP Filippo De Santis - [email protected] - @filippodesantis
  • 2. Design pattern in PHP Web developer Working in @ideato since 2009 XP and Kanban user
  • 3. Design pattern in PHP What is a design pattern?
  • 4. Design pattern in PHP What is a design pattern? “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” Christopher Alexander
  • 5. Design pattern in PHP What is a design pattern? “A pattern is a [general] solution to a problem in a context” Gang of four
  • 6. Design pattern in PHP Elements of a design pattern Name Used to describe a design problem, its solution and its consequences in a word or two
  • 7. Design pattern in PHP Elements of a design pattern Problem Describes when to apply a pattern
  • 8. Design pattern in PHP Elements of a design pattern Solution Describes the elements that make up the design, their relationships, responsibilities, and collaborations
  • 9. Design pattern in PHP Elements of a design pattern Consequences The results and trade-offs of applying the pattern
  • 10. Design pattern in PHP Singleton
  • 11. Design pattern in PHP Singleton Ensures that a class has one instance only Provides a global point of access to it
  • 12. Design pattern in PHP Singleton Access control Only one instance YES!
  • 13. Design pattern in PHP Singleton Used to replace global variables [changing the name does not change the problem] Violates the Single Responsibility Principle [creation + singleton class functionality] NO!
  • 14. Design pattern in PHP Singleton private function __construct() {}
  • 15. Design pattern in PHP Singleton private static $instance = false;
  • 16. Design pattern in PHP Singleton public static function getInstance() { if (false == self::$instance) { self::$instance = new self(); } return self::$instance; }
  • 17. Design pattern in PHP Singleton class Singleton { private static $instance = false; private function __construct() {} public static function getInstance() { if (false == self::$instance) { self::$instance = new self(); } return self::$instance; } } $instance = Singleton::getInstance();
  • 18. Design pattern in PHP Factory method
  • 19. Design pattern in PHP Factory method Classes delegate responsibility of building objets Localize the knowledge of which class is the delegate
  • 20. Design pattern in PHP Factory method PHP most used implementation: Parameterized factory method
  • 21. Design pattern in PHP Factory method class Factory { public function build($condition) {...} }
  • 22. Design pattern in PHP Factory method interface Document { ... }
  • 23. Design pattern in PHP Factory method MyDoc implements Document {...} YourDoc implements Document {...} TheirDoc implements Document {...}
  • 24. Design pattern in PHP Factory method class Factory { /* @return Document */ public function build($condition) {...} }
  • 25. Design pattern in PHP Factory method class DocumentReaderFactory { public function build($type) { switch ($type) { case 'txt': return new TxtReader(); case 'doc': return new DocReader(); //... } } } foreach ($documents as $document) { $factory = new DocumentReaderFactory(); $reader = $factory->build($document->getType()); $reader->read($document); }
  • 26. Design pattern in PHP Adapter
  • 27. Design pattern in PHP Adapter Converts the interface of a class into another interface
  • 28. Design pattern in PHP Adapter An existing class interface does not match what you need To create a reusable class
  • 29. Design pattern in PHP Adapter interface AdapterInterface { ... }
  • 30. Design pattern in PHP Adapter by class inheritance Adapter exteds Adaptee implements AdapterInterface { ... }
  • 31. Design pattern in PHP Adapter by objects composition Adapter implements AdapterInterface { public function __construct(Adaptee $adaptee){ $this->adaptee = $adaptee; } ... }
  • 32. Design pattern in PHP Adapter interface FileOperationsInterface { public function getContent($filename); public function putContent($filename, $data); public function removeFile($filename); }
  • 33. Design pattern in PHP Adapter by class inheritance class FTPFileAdapter extends FTPFileRepository implements FileOperationsInterface { public function getContent($filename) { … } public function putContent($local_file, $data) { … } public function removeFile($filename) { … } }
  • 34. Design pattern in PHP Adapter class FTPFileAdapter implements FileOperationsInterface { by objects composition public function __construct(FTPFileRepository $repository) { $this->repository = $repository; } public function getContent($filename) { $this->repository->download($local_file, $filename); return file_get_content($local_file); } public function putContent($local_file, $data) { file_put_contents($local_file, $data); $this->repository->upload($remote_file, $local_file); } public function removeFile($filename){ $this->repository->remove($filename); } }
  • 35. Design pattern in PHP Template method
  • 36. Design pattern in PHP Template method Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses
  • 37. Design pattern in PHP Template method Implements the invariant parts of an algorithm once Leaves it up to subclasses the behavior that can vary Common behavior localized in a common class To control subclasses extensions
  • 38. Design pattern in PHP Template method Classes implementing a template method should: specify hooks (may be overridden) specify abstract operations (must be overridden)
  • 39. Design pattern in PHP Template method abstract operations (must be overridden) ie: use prefix “DO” DoRead() DoWrite() DoSomething()
  • 40. Design pattern in PHP Template method abstract class Reader { abstract protected function openFile($filename); abstract protected function readFile(); abstract protected function closeFile(); public function readFileAlgorithm($filename) { $this->openFile($filename); $content = $this->readFile(); $this->closeFile(); return $content }
  • 41. Design pattern in PHPmethod Template class XMLReader extends Reader { protected function openFile($filename) { $this->xml = simplexml_load_file($filename); } protected function readFile() { return $this->xml->description; } public function closeFile(){} }
  • 42. Design pattern in PHPmethod Template class CSVReader extends Reader { protected function openFile($filename) { $this->handle = fopen($filename, "r"); } protected function closeFile() { fclose($this->handle); } protected function readFile() { $data = fgetcsv($this->handle); return $data[3]; //description } }
  • 43. Design pattern in PHPmethod Template Hooks class Parent { protected function hook() {} public function doSomething() { //... $this->hook(); } }
  • 44. Design pattern in PHPmethod Template Hooks class Child extends Parent { protected function hook() { //My logic to add into the doSomething method } }
  • 45. Design pattern in PHP Dependency Injection
  • 46. Design pattern in PHP Dependency Injection Components are given their dependencies through their constructors, methods, or directly into fields
  • 47. Design pattern in PHP Dependency Injection Those components do not get their dependencies themselves, or instantiate them directly
  • 48. Design pattern in PHP Dependency Injection class A { public function doSomething() { $b = new B(); //... } } NO!
  • 49. Design pattern in PHP Dependency Injection class A { public function construct(B $b) { $this->b = $b; } //... } YES!
  • 50. Design pattern in PHP Dependency Injection class A { public function setB(B $b) { $this->b = $b; } //... } YES!
  • 51. Design pattern in PHP Dependency Injection class A { public $b; //... } $a = new A(); $a->b = new B(); YES!
  • 52. Design pattern in PHP Dependency Injection class A implements DiInterface{ } interface DiInterface { public function setB(B $b); } YES!
  • 53. Design pattern in PHP Dependency Injection Container Dependency & Injection Inversion of control
  • 54. References Design Patterns: Elements of Reusable Object-Oriented Software E. Gamma, R. Helm, R. Johnson, J.Vlissides Addison-Wesley 1974 Martin Fowler - http://martinfowler.com/bliki/InversionOfControl.html PicoContainer Documentation: http://picocontainer.org/injection.html SourceMaking - Design Patterns: http://sourcemaking.com/design_patterns PHP best practices - Pattern in PHP: http://www.phpbestpractices.it
  • 55. Thank you! Filippo De Santis - [email protected] - @filippodesantis