SlideShare ist ein Scribd-Unternehmen logo
1 von 55
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
PHP Annotations: They exist! - JetBrains Webinar
 PHP Annotations: They exist! - JetBrains Webinar PHP Annotations: They exist! - JetBrains Webinar
PHP Annotations: They exist! - JetBrains Webinar
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
More about PHP
More about PHPMore about PHP
More about PHP
 
Presentation
PresentationPresentation
Presentation
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
Php introduction and configuration
Php introduction and configurationPhp introduction and configuration
Php introduction and configuration
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
 
Project Automation
Project AutomationProject Automation
Project Automation
 

Andere mochten auch

Xkanban V3: eXtreme Programming, Kanban and Timboxing
Xkanban V3: eXtreme Programming, Kanban and TimboxingXkanban V3: eXtreme Programming, Kanban and Timboxing
Xkanban V3: eXtreme Programming, Kanban and TimboxingFilippo De Santis
 
Vsena.Foss.Migration.Guide.V1.01
Vsena.Foss.Migration.Guide.V1.01Vsena.Foss.Migration.Guide.V1.01
Vsena.Foss.Migration.Guide.V1.01vsena
 
Intro to Publishing iOS Apps - Full Cycle
Intro to Publishing iOS Apps - Full CycleIntro to Publishing iOS Apps - Full Cycle
Intro to Publishing iOS Apps - Full CycleDynamit
 
AméRica En El Mundo
AméRica En El MundoAméRica En El Mundo
AméRica En El MundoIsa Espinoza
 
VEKO digital marketing 12 2010
VEKO digital marketing 12 2010VEKO digital marketing 12 2010
VEKO digital marketing 12 2010Antti Leino
 
xkanban v2 (ALE Bathtub III)
xkanban v2 (ALE Bathtub III)xkanban v2 (ALE Bathtub III)
xkanban v2 (ALE Bathtub III)Filippo De Santis
 
VEKO13 Joulu 2009
VEKO13 Joulu 2009VEKO13 Joulu 2009
VEKO13 Joulu 2009Antti Leino
 
Symfony2: the world slowest framework
Symfony2: the world slowest frameworkSymfony2: the world slowest framework
Symfony2: the world slowest frameworkFilippo De Santis
 
Building a-self-sufficient-team
Building a-self-sufficient-teamBuilding a-self-sufficient-team
Building a-self-sufficient-teamFilippo De Santis
 
Applied linear algebra
Applied linear algebraApplied linear algebra
Applied linear algebrarch850 -
 
Sosiaalinen media: yhteisöt, sisältö & keskustelut
Sosiaalinen media: yhteisöt, sisältö & keskustelutSosiaalinen media: yhteisöt, sisältö & keskustelut
Sosiaalinen media: yhteisöt, sisältö & keskustelutAntti Leino
 
Sosiaalinen media työnhaussa
Sosiaalinen media työnhaussaSosiaalinen media työnhaussa
Sosiaalinen media työnhaussaAntti Leino
 
5 Digital Trends for 2013 - Dynamit
5 Digital Trends for 2013 - Dynamit 5 Digital Trends for 2013 - Dynamit
5 Digital Trends for 2013 - Dynamit Dynamit
 
Youarealwaysonmymind
YouarealwaysonmymindYouarealwaysonmymind
Youarealwaysonmymindguest2e7d1e7
 
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempi
Symfony2  per utenti Symfony 1.x: Architettura, modelli ed esempiSymfony2  per utenti Symfony 1.x: Architettura, modelli ed esempi
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempiFilippo De Santis
 
Suggestions and Ideas for DigitalOcean
Suggestions and Ideas for DigitalOceanSuggestions and Ideas for DigitalOcean
Suggestions and Ideas for DigitalOceanKaan Caliskan
 
Arquitectura I Escultura Grega
Arquitectura I Escultura GregaArquitectura I Escultura Grega
Arquitectura I Escultura Gregaguestd4825b
 

Andere mochten auch (20)

Xkanban V3: eXtreme Programming, Kanban and Timboxing
Xkanban V3: eXtreme Programming, Kanban and TimboxingXkanban V3: eXtreme Programming, Kanban and Timboxing
Xkanban V3: eXtreme Programming, Kanban and Timboxing
 
Vsena.Foss.Migration.Guide.V1.01
Vsena.Foss.Migration.Guide.V1.01Vsena.Foss.Migration.Guide.V1.01
Vsena.Foss.Migration.Guide.V1.01
 
Intro to Publishing iOS Apps - Full Cycle
Intro to Publishing iOS Apps - Full CycleIntro to Publishing iOS Apps - Full Cycle
Intro to Publishing iOS Apps - Full Cycle
 
AméRica En El Mundo
AméRica En El MundoAméRica En El Mundo
AméRica En El Mundo
 
VEKO digital marketing 12 2010
VEKO digital marketing 12 2010VEKO digital marketing 12 2010
VEKO digital marketing 12 2010
 
xkanban v2 (ALE Bathtub III)
xkanban v2 (ALE Bathtub III)xkanban v2 (ALE Bathtub III)
xkanban v2 (ALE Bathtub III)
 
VEKO13 Joulu 2009
VEKO13 Joulu 2009VEKO13 Joulu 2009
VEKO13 Joulu 2009
 
Easy Notes V1.0 En
Easy Notes V1.0 EnEasy Notes V1.0 En
Easy Notes V1.0 En
 
Symfony2: the world slowest framework
Symfony2: the world slowest frameworkSymfony2: the world slowest framework
Symfony2: the world slowest framework
 
Building a-self-sufficient-team
Building a-self-sufficient-teamBuilding a-self-sufficient-team
Building a-self-sufficient-team
 
Applied linear algebra
Applied linear algebraApplied linear algebra
Applied linear algebra
 
Sosiaalinen media: yhteisöt, sisältö & keskustelut
Sosiaalinen media: yhteisöt, sisältö & keskustelutSosiaalinen media: yhteisöt, sisältö & keskustelut
Sosiaalinen media: yhteisöt, sisältö & keskustelut
 
Sosiaalinen media työnhaussa
Sosiaalinen media työnhaussaSosiaalinen media työnhaussa
Sosiaalinen media työnhaussa
 
Medical Microbiology Lab
Medical Microbiology LabMedical Microbiology Lab
Medical Microbiology Lab
 
5 Digital Trends for 2013 - Dynamit
5 Digital Trends for 2013 - Dynamit 5 Digital Trends for 2013 - Dynamit
5 Digital Trends for 2013 - Dynamit
 
Mémoire Estonie
Mémoire EstonieMémoire Estonie
Mémoire Estonie
 
Youarealwaysonmymind
YouarealwaysonmymindYouarealwaysonmymind
Youarealwaysonmymind
 
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempi
Symfony2  per utenti Symfony 1.x: Architettura, modelli ed esempiSymfony2  per utenti Symfony 1.x: Architettura, modelli ed esempi
Symfony2 per utenti Symfony 1.x: Architettura, modelli ed esempi
 
Suggestions and Ideas for DigitalOcean
Suggestions and Ideas for DigitalOceanSuggestions and Ideas for DigitalOcean
Suggestions and Ideas for DigitalOcean
 
Arquitectura I Escultura Grega
Arquitectura I Escultura GregaArquitectura I Escultura Grega
Arquitectura I Escultura Grega
 

Ähnlich wie Design attern in php

10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
PHP in one presentation
PHP in one presentationPHP in one presentation
PHP in one presentationMilad Rahimi
 
Phpspec tips&tricks
Phpspec tips&tricksPhpspec tips&tricks
Phpspec tips&tricksFilip Golonka
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)Oleg Zinchenko
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7ZendVN
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Stephan Schmidt
 

Ähnlich wie Design attern in php (20)

OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
OOP
OOPOOP
OOP
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
PHP in one presentation
PHP in one presentationPHP in one presentation
PHP in one presentation
 
Phpspec tips&tricks
Phpspec tips&tricksPhpspec tips&tricks
Phpspec tips&tricks
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
 
Reflection-In-PHP
Reflection-In-PHPReflection-In-PHP
Reflection-In-PHP
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 

Kürzlich hochgeladen

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Design attern in php

  • 1. Design pattern in PHP Filippo De Santis - fd@ideato.it - @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 - fd@ideato.it - @filippodesantis