SlideShare a Scribd company logo
1 of 37
Classic Design Patterns in PHP

                          Part One

                        Download Code Samples




  www.LifeMichael.com                           www.abelski.com
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, Sara Ishikawa, Murray Silverstein, Max Jacobson, Ingrid Fiksdahl-King and
                                 Shlomo Angel. A Pattern Language. Oxford University Press, New York, 1977.




09/15/11                             (c) 2011 Haim Michael. All Rights Reserved.                                2
Software Design Pattern?

           “Software patterns are reusable solutions to recurring
           problems that we encounter during software development.”

                                            Mark Grand, Patterns in Java. John Wiley & Sons, 2002.




09/15/11                   (c) 2011 Haim Michael. All Rights Reserved.                               3
History
     The idea of using patterns evolves from the architecture field.
           Christopher Alexander. A Pattern Language: Towns, Buildings, Construction
           (Oxford University Press, 1977)

     The first GUI software patterns were set in 1987.
           Ward Cunningham and Kent Beck. Using Pattern Languages for Object-Oriented
           Programs. OOPSLA-87.

     The Gang of Four (AKA GOF) publish their “Design Patterns”
           book in 1994.
           Erich Gamma, Richard Helm, John Vlissides, and Ralph Johnson. Design
           Patterns. Addison Wesley, 1994.

09/15/11                         (c) 2011 Haim Michael. All Rights Reserved.            4
History

                          This book defines 23 design patterns.

                          The design patterns are grouped
                          into three categories:
                          Creational Patterns
                          Behavioral Patterns
                          Structural Patterns




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.       5
Why?
     Design patterns are language independent. Using design
           patterns we might improve our code.

     Design patterns define a vocabulary. The communication
           between developers within teams can improve.

     Design patters were already tested by other developers in
           other software systems.

     Using design patterns in general assist us with the
           development of a better software.

09/15/11                   (c) 2011 Haim Michael. All Rights Reserved.   6
Singleton
     Problem Description
           How to declare a class ensuring that it won't be possible to instantiate it more than
           once.

     General Solution
           We can declare a class with one (or more) private constructors only and include
           within that class a static method that once is called it checks whether an object of
           this class was already instantiated... if an object was already created then that
           static method will return its reference... if an object still wasn't created then it will
           instantiate this class, places the reference for the new object within a specific
           static variable and return it.



09/15/11                           (c) 2011 Haim Michael. All Rights Reserved.                         7
Singleton




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   8
Singleton
           <?php
           class Inventory
           {
              private static $single;
              private function __construct() { }
              public static function getInstance()
              {
                  if(self::$single==null)
                  {
                     self::$single = new Inventory();
                  }
                  return Inventory::$single;
              }
           }
           ?>

                     Watch Additional Video Clip



09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   9
Factory

    Problem Description
       How to create an object of a type selected based on external data received in run
       time, without having the need to be aware of the actual type of the new created
       object.

    General Solution
       We will define an interface for creating new objects and let subclasses to decide
       about the exact class that should be instantiated according to the received
       arguments.




09/15/11                      (c) 2011 Haim Michael. All Rights Reserved.                  10
Factory




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   11
Factory
      <?php
      class AnimalsFactory
      {
          public static function getAnimal($str)
          {
              if($str=="cat")
              {                                      Watch Additional Video Clip
                  return new Cat();
              }
              else if($str=="tiger")
              {
                  $ob = new Cat();
                  $ob->setCatType("tiger");
                  return $ob;
              }
              else if($str=="dog")
              {
                  return new Dog();
              }
              throw new Exception('animal type doesnot exist');
          }
      }


09/15/11                     (c) 2011 Haim Michael. All Rights Reserved.           12
Factory
      class Cat
      {
          private $catType;
          function __toString()
          {
              return "cat " . $this->catType;
          }
          function setCatType($str)
          {
              $this->catType = $str;
          }
      }

      class Dog
      {
          function __toString()
          {
              return "dog";
          }
      }
      ?>



09/15/11                  (c) 2011 Haim Michael. All Rights Reserved.   13
Proxy

     Problem Description
           How to ensure that a costly object will be instantiated on demand (only when we
           actually need it).

     General Solution
           Define a class that its objects will be able to maintain a reference for the costly
           object and will be capable of creating it (on demand... when there is a need for it).




09/15/11                          (c) 2011 Haim Michael. All Rights Reserved.                      14
Proxy




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   15
Proxy
      <?php
      interface IVideo
      {
         function play();
      }

      class Video implements IVideo
      {
         private $title;
         public function __construct($title)
         {
             $this->title = $title;
         }
         public function play()
         {
             echo "playing ".$this->title." video";
         }
      }

                Watch Additional Video Clip


09/15/11                    (c) 2011 Haim Michael. All Rights Reserved.   16
Proxy
      class VideoProxy implements IVideo
      {
         private $video;
         private $title;
         public function __construct($str)
         {
             $this->title = $str;
         }
         public function play()
         {
             if($this->video==null)
                $this->video = new Video($this->title);
             $this->video->play();
         }

      }

      $ob = new VideoProxy("XMania III");
      $ob->play();
      ?>

09/15/11               (c) 2011 Haim Michael. All Rights Reserved.   17
Template
     Problem Description
           How to define a skeleton of algorithm allowing to defer some of its steps to the
           subclasses... ?

     General Solution
           We will define an abstract class with a concrete method that implements the
           algorithm by calling abstract methods declared in the same class. Classes that
           extend our abstract class will include their implementations for these abstract
           methods.




09/15/11                          (c) 2011 Haim Michael. All Rights Reserved.                 18
Template




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   19
Template
   <?php

   abstract class Shape
   {
      public abstract function area();
      public function __toString()
      {
         return "my area is ".$this->area();
      }
   }

            Watch Additional Video Clip




09/15/11                   (c) 2011 Haim Michael. All Rights Reserved.   20
Template
    class Circle extends Shape
    {
        private $radius;
        public function __construct($rad)
        {
            $this->setRadius($rad);
        }
        public function getRadius()
        {
            return $this->radius;
        }
        public function setRadius($radius)
        {
            $this->radius = $radius;
        }
        public function area()
        {
            return pi()*$this->getRadius()*$this->getRadius();
        }
    }



09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   21
Template
   class Rectangle extends Shape
   {
       private $width;
       private $height;
       public function __construct($wVal, $hVal)
       {
           $this->setWidth($wVal);
           $this->setHeight($hVal);
       }
       public function getWidth()
       {
           return $this->width;
       }
       public function setWidth($width)
       {
           $this->width = $width;
       }
       public function getHeight()
       {
           return $this->height;
       }



09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   22
Template
           public function setHeight($height)
           {
               $this->height = $height;
           }
           public function area()
           {
               return $this->getWidth()*$this->getHeight();
           }
   }

   $vec = array(new Rectangle(3,4), new Circle(5), new Rectangle(5,4));
   foreach($vec as $ob)
   {
       echo "<br>".$ob;
   }

   ?>




09/15/11                     (c) 2011 Haim Michael. All Rights Reserved.   23
Decorator
     Problem Description
           How to extend the functionality of a given object in a way that is transparent for its
           clients without sub classing the given object.

     General Solution
           Declaring a new class, that implements the same interface the original object
           implements and delegates operations to the original given object.




09/15/11                          (c) 2011 Haim Michael. All Rights Reserved.                   24
Decorator




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   25
Decorator

      <?php
      interface IBook
      {
         function setTitle($str);
         function getTitle();
         function setPages($num);
         function getPages();
         function setAuthor($author);
         function getAuthor();
      }


                Watch Additional Video Clip




09/15/11                    (c) 2011 Haim Michael. All Rights Reserved.   26
Decorator

      final class StandardBook implements IBook
      {
         private $author;
         private $title;
         private $pages;

           public function getAuthor()
           {
              return $this->author;
           }

           public function getPages()
           {
              return $this->pages;
           }




09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   27
Decorator
           public function getTitle()
           {
               return $this->title;
           }

           public function setAuthor($author)
           {
               $this->author = $author;
           }

           public function setPages($pages)
           {
               $this->pages = $pages;
           }

           public function setTitle($title)
           {
               $this->title = $title;
           }
      }

      interface ILibraryBook extends IBook
      {
          function printDetails();
      }

09/15/11                    (c) 2011 Haim Michael. All Rights Reserved.   28
Decorator
      class LibraryBook implements ILibraryBook
      {
         private $book;

           public function __construct()
           {
              $this->book = new StandardBook();
           }

           public function printDetails()
           {
              echo "<br>author=".$this->book->getAuthor();
              echo "<br>pages=".$this->book->getPages();
              echo "<br>title=".$this->book->getTitle();
           }




09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   29
Decorator
           public function getAuthor()
           {
              return $this->book->getAuthor();
           }

           public function getPages()
           {
              return $this->book->getPages();
           }

           public function getTitle()
           {
              return $this->book->getTitle();
           }

           public function setAuthor($str)
           {
              $this->book->setAuthor($str);
           }

09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   30
Decorator
           public function setPages($num)
           {
              $this->book->setPages($num);
           }

           public function setTitle($str)
           {
              $this->book->setTitle($str);
           }
      }

      $book = new LibraryBook();
      $book->setAuthor("haim");
      $book->setPages(320);
      $book->setTitle("core scala");
      $book->printDetails();

      ?>


09/15/11                 (c) 2011 Haim Michael. All Rights Reserved.   31
Prototype
     Problem Description
           How to create new objects based on a prototype object we already have, without
           knowing their exact class or the details of how to create them.

     General Solution
           We will declare an abstract class that includes the clone() method. When calling
           the clone() method a new object is instantiated from the same class the object (on
           which the clone() method is called) was instantiated from.




09/15/11                         (c) 2011 Haim Michael. All Rights Reserved.                  32
Prototype




09/15/11   (c) 2011 Haim Michael. All Rights Reserved.   33
Prototype
      <?php
      interface Duplicatable
      {
          function duplicate();
      }

      class Circle implements Duplicatable
      {
          private $radius;
          public function __construct($rad)
          {
              $this->setRadius($rad);
          }
          public function getRadius()
          {
              return $this->radius;
          }
          public function setRadius($radius)
          {
              $this->radius = $radius;
          }
                                                                  Watch Additional Video Clip


09/15/11                   (c) 2011 Haim Michael. All Rights Reserved.                          34
Prototype
           public function duplicate()
           {
               return new Circle($this->getRadius());
           }
           public function area()
           {
               return pi()*$this->getRadius()*$this->getRadius();
           }
           public function __toString()
           {
               return "i m a circle... my area is ".$this->area();
           }
      }




09/15/11                    (c) 2011 Haim Michael. All Rights Reserved.   35
Prototype
      class Rectangle implements Duplicatable
      {
          private $width;
          private $height;
          public function __construct($wVal, $hVal)
          {
              $this->setWidth($wVal);
              $this->setHeight($hVal);
          }
          public function getWidth()
          {
              return $this->width;
          }
          public function setWidth($width)
          {
              $this->width = $width;
          }
          public function getHeight()
          {
              return $this->height;
          }



09/15/11                   (c) 2011 Haim Michael. All Rights Reserved.   36
Prototype
           public function setHeight($height)
           {
               $this->height = $height;
           }
           public function duplicate()
           {
               return new Rectangle($this->getWidth(),$this->getHeight());
           }
           public function area()
           {
               return $this->getWidth()*$this->getHeight();
           }
           public function __toString()
           {
               return "i m a rectangle... my area is ".$this->area();
           }
      }

      $obA = new Circle(3);
      $obB = $obA->duplicate();
      echo $obB;

      ?>


09/15/11                    (c) 2011 Haim Michael. All Rights Reserved.      37

More Related Content

Viewers also liked

Beyond design patterns phpnw14
Beyond design patterns   phpnw14Beyond design patterns   phpnw14
Beyond design patterns phpnw14Anthony Ferrara
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Patternguy_davis
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksPhill Sparks
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015Vic Tarchenko
 

Viewers also liked (7)

Design patterns - Decorator pattern
Design patterns -   Decorator patternDesign patterns -   Decorator pattern
Design patterns - Decorator pattern
 
Beyond design patterns phpnw14
Beyond design patterns   phpnw14Beyond design patterns   phpnw14
Beyond design patterns phpnw14
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill Sparks
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015
 

Similar to WEBINAR: Classic Design Patterns in PHP

27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examplesQuang Suma
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Clean Code Part I - Design Patterns at SoCal Code Camp
Clean Code Part I - Design Patterns at SoCal Code CampClean Code Part I - Design Patterns at SoCal Code Camp
Clean Code Part I - Design Patterns at SoCal Code CampTheo Jungeblut
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of featuresvidyamittal
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)David McCarter
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Savio Sebastian
 
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...Theo Jungeblut
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Design pattern - part 1
Design pattern - part 1Design pattern - part 1
Design pattern - part 1Jieyi Wu
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonAEM HUB
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling RewriterJustin Edelson
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCJohnKennedy
 

Similar to WEBINAR: Classic Design Patterns in PHP (20)

27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Clean Code Part I - Design Patterns at SoCal Code Camp
Clean Code Part I - Design Patterns at SoCal Code CampClean Code Part I - Design Patterns at SoCal Code Camp
Clean Code Part I - Design Patterns at SoCal Code Camp
 
Test Engine
Test EngineTest Engine
Test Engine
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
 
Object
ObjectObject
Object
 
.NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012).NET Coding Standards For The Real World (2012)
.NET Coding Standards For The Real World (2012)
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
Clean Code - Design Patterns and Best Practices for Bay.NET SF User Group (01...
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Design pattern - part 1
Design pattern - part 1Design pattern - part 1
Design pattern - part 1
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Mastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin EdelsonMastering the Sling Rewriter by Justin Edelson
Mastering the Sling Rewriter by Justin Edelson
 
Mastering the Sling Rewriter
Mastering the Sling RewriterMastering the Sling Rewriter
Mastering the Sling Rewriter
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveC
 

More from Zend by Rogue Wave Software

Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM iZend by Rogue Wave Software
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Zend by Rogue Wave Software
 
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)Zend by Rogue Wave Software
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Zend by Rogue Wave Software
 

More from Zend by Rogue Wave Software (20)

Develop microservices in php
Develop microservices in phpDevelop microservices in php
Develop microservices in php
 
Speed and security for your PHP application
Speed and security for your PHP applicationSpeed and security for your PHP application
Speed and security for your PHP application
 
Building and managing applications fast for IBM i
Building and managing applications fast for IBM iBuilding and managing applications fast for IBM i
Building and managing applications fast for IBM i
 
Building web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend ExpressiveBuilding web APIs in PHP with Zend Expressive
Building web APIs in PHP with Zend Expressive
 
To PHP 7 and beyond
To PHP 7 and beyondTo PHP 7 and beyond
To PHP 7 and beyond
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)The Sodium crypto library of PHP 7.2 (PHP Day 2018)
The Sodium crypto library of PHP 7.2 (PHP Day 2018)
 
Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)Develop web APIs in PHP using middleware with Expressive (Code Europe)
Develop web APIs in PHP using middleware with Expressive (Code Europe)
 
Middleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.xMiddleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.x
 
Ongoing management of your PHP 7 application
Ongoing management of your PHP 7 applicationOngoing management of your PHP 7 application
Ongoing management of your PHP 7 application
 
Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7
 
The Docker development template for PHP
The Docker development template for PHPThe Docker development template for PHP
The Docker development template for PHP
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Unit testing for project managers
Unit testing for project managersUnit testing for project managers
Unit testing for project managers
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Deploying PHP apps on the cloud
Deploying PHP apps on the cloudDeploying PHP apps on the cloud
Deploying PHP apps on the cloud
 
Data is dead. Long live data!
Data is dead. Long live data! Data is dead. Long live data!
Data is dead. Long live data!
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 
Resolving problems & high availability
Resolving problems & high availabilityResolving problems & high availability
Resolving problems & high availability
 
Developing apps faster
Developing apps fasterDeveloping apps faster
Developing apps faster
 

Recently uploaded

Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosErol GIRAUDY
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)codyslingerland1
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.IPLOOK Networks
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarThousandEyes
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...DianaGray10
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingMAGNIntelligence
 

Recently uploaded (20)

Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 
Scenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenariosScenario Library et REX Discover industry- and role- based scenarios
Scenario Library et REX Discover industry- and role- based scenarios
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)The New Cloud World Order Is FinOps (Slideshow)
The New Cloud World Order Is FinOps (Slideshow)
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
EMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? WebinarEMEA What is ThousandEyes? Webinar
EMEA What is ThousandEyes? Webinar
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced Computing
 

WEBINAR: Classic Design Patterns in PHP

  • 1. Classic Design Patterns in PHP Part One Download Code Samples www.LifeMichael.com www.abelski.com
  • 2. 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, Sara Ishikawa, Murray Silverstein, Max Jacobson, Ingrid Fiksdahl-King and Shlomo Angel. A Pattern Language. Oxford University Press, New York, 1977. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 2
  • 3. Software Design Pattern? “Software patterns are reusable solutions to recurring problems that we encounter during software development.” Mark Grand, Patterns in Java. John Wiley & Sons, 2002. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 3
  • 4. History  The idea of using patterns evolves from the architecture field. Christopher Alexander. A Pattern Language: Towns, Buildings, Construction (Oxford University Press, 1977)  The first GUI software patterns were set in 1987. Ward Cunningham and Kent Beck. Using Pattern Languages for Object-Oriented Programs. OOPSLA-87.  The Gang of Four (AKA GOF) publish their “Design Patterns” book in 1994. Erich Gamma, Richard Helm, John Vlissides, and Ralph Johnson. Design Patterns. Addison Wesley, 1994. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 4
  • 5. History This book defines 23 design patterns. The design patterns are grouped into three categories: Creational Patterns Behavioral Patterns Structural Patterns 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 5
  • 6. Why?  Design patterns are language independent. Using design patterns we might improve our code.  Design patterns define a vocabulary. The communication between developers within teams can improve.  Design patters were already tested by other developers in other software systems.  Using design patterns in general assist us with the development of a better software. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 6
  • 7. Singleton  Problem Description How to declare a class ensuring that it won't be possible to instantiate it more than once.  General Solution We can declare a class with one (or more) private constructors only and include within that class a static method that once is called it checks whether an object of this class was already instantiated... if an object was already created then that static method will return its reference... if an object still wasn't created then it will instantiate this class, places the reference for the new object within a specific static variable and return it. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 7
  • 8. Singleton 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 8
  • 9. Singleton <?php class Inventory { private static $single; private function __construct() { } public static function getInstance() { if(self::$single==null) { self::$single = new Inventory(); } return Inventory::$single; } } ?> Watch Additional Video Clip 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 9
  • 10. Factory  Problem Description How to create an object of a type selected based on external data received in run time, without having the need to be aware of the actual type of the new created object.  General Solution We will define an interface for creating new objects and let subclasses to decide about the exact class that should be instantiated according to the received arguments. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 10
  • 11. Factory 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 11
  • 12. Factory <?php class AnimalsFactory { public static function getAnimal($str) { if($str=="cat") { Watch Additional Video Clip return new Cat(); } else if($str=="tiger") { $ob = new Cat(); $ob->setCatType("tiger"); return $ob; } else if($str=="dog") { return new Dog(); } throw new Exception('animal type doesnot exist'); } } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 12
  • 13. Factory class Cat { private $catType; function __toString() { return "cat " . $this->catType; } function setCatType($str) { $this->catType = $str; } } class Dog { function __toString() { return "dog"; } } ?> 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 13
  • 14. Proxy  Problem Description How to ensure that a costly object will be instantiated on demand (only when we actually need it).  General Solution Define a class that its objects will be able to maintain a reference for the costly object and will be capable of creating it (on demand... when there is a need for it). 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 14
  • 15. Proxy 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 15
  • 16. Proxy <?php interface IVideo { function play(); } class Video implements IVideo { private $title; public function __construct($title) { $this->title = $title; } public function play() { echo "playing ".$this->title." video"; } } Watch Additional Video Clip 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 16
  • 17. Proxy class VideoProxy implements IVideo { private $video; private $title; public function __construct($str) { $this->title = $str; } public function play() { if($this->video==null) $this->video = new Video($this->title); $this->video->play(); } } $ob = new VideoProxy("XMania III"); $ob->play(); ?> 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 17
  • 18. Template  Problem Description How to define a skeleton of algorithm allowing to defer some of its steps to the subclasses... ?  General Solution We will define an abstract class with a concrete method that implements the algorithm by calling abstract methods declared in the same class. Classes that extend our abstract class will include their implementations for these abstract methods. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 18
  • 19. Template 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 19
  • 20. Template <?php abstract class Shape { public abstract function area(); public function __toString() { return "my area is ".$this->area(); } } Watch Additional Video Clip 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 20
  • 21. Template class Circle extends Shape { private $radius; public function __construct($rad) { $this->setRadius($rad); } public function getRadius() { return $this->radius; } public function setRadius($radius) { $this->radius = $radius; } public function area() { return pi()*$this->getRadius()*$this->getRadius(); } } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 21
  • 22. Template class Rectangle extends Shape { private $width; private $height; public function __construct($wVal, $hVal) { $this->setWidth($wVal); $this->setHeight($hVal); } public function getWidth() { return $this->width; } public function setWidth($width) { $this->width = $width; } public function getHeight() { return $this->height; } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 22
  • 23. Template public function setHeight($height) { $this->height = $height; } public function area() { return $this->getWidth()*$this->getHeight(); } } $vec = array(new Rectangle(3,4), new Circle(5), new Rectangle(5,4)); foreach($vec as $ob) { echo "<br>".$ob; } ?> 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 23
  • 24. Decorator  Problem Description How to extend the functionality of a given object in a way that is transparent for its clients without sub classing the given object.  General Solution Declaring a new class, that implements the same interface the original object implements and delegates operations to the original given object. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 24
  • 25. Decorator 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 25
  • 26. Decorator <?php interface IBook { function setTitle($str); function getTitle(); function setPages($num); function getPages(); function setAuthor($author); function getAuthor(); } Watch Additional Video Clip 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 26
  • 27. Decorator final class StandardBook implements IBook { private $author; private $title; private $pages; public function getAuthor() { return $this->author; } public function getPages() { return $this->pages; } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 27
  • 28. Decorator public function getTitle() { return $this->title; } public function setAuthor($author) { $this->author = $author; } public function setPages($pages) { $this->pages = $pages; } public function setTitle($title) { $this->title = $title; } } interface ILibraryBook extends IBook { function printDetails(); } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 28
  • 29. Decorator class LibraryBook implements ILibraryBook { private $book; public function __construct() { $this->book = new StandardBook(); } public function printDetails() { echo "<br>author=".$this->book->getAuthor(); echo "<br>pages=".$this->book->getPages(); echo "<br>title=".$this->book->getTitle(); } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 29
  • 30. Decorator public function getAuthor() { return $this->book->getAuthor(); } public function getPages() { return $this->book->getPages(); } public function getTitle() { return $this->book->getTitle(); } public function setAuthor($str) { $this->book->setAuthor($str); } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 30
  • 31. Decorator public function setPages($num) { $this->book->setPages($num); } public function setTitle($str) { $this->book->setTitle($str); } } $book = new LibraryBook(); $book->setAuthor("haim"); $book->setPages(320); $book->setTitle("core scala"); $book->printDetails(); ?> 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 31
  • 32. Prototype  Problem Description How to create new objects based on a prototype object we already have, without knowing their exact class or the details of how to create them.  General Solution We will declare an abstract class that includes the clone() method. When calling the clone() method a new object is instantiated from the same class the object (on which the clone() method is called) was instantiated from. 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 32
  • 33. Prototype 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 33
  • 34. Prototype <?php interface Duplicatable { function duplicate(); } class Circle implements Duplicatable { private $radius; public function __construct($rad) { $this->setRadius($rad); } public function getRadius() { return $this->radius; } public function setRadius($radius) { $this->radius = $radius; } Watch Additional Video Clip 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 34
  • 35. Prototype public function duplicate() { return new Circle($this->getRadius()); } public function area() { return pi()*$this->getRadius()*$this->getRadius(); } public function __toString() { return "i m a circle... my area is ".$this->area(); } } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 35
  • 36. Prototype class Rectangle implements Duplicatable { private $width; private $height; public function __construct($wVal, $hVal) { $this->setWidth($wVal); $this->setHeight($hVal); } public function getWidth() { return $this->width; } public function setWidth($width) { $this->width = $width; } public function getHeight() { return $this->height; } 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 36
  • 37. Prototype public function setHeight($height) { $this->height = $height; } public function duplicate() { return new Rectangle($this->getWidth(),$this->getHeight()); } public function area() { return $this->getWidth()*$this->getHeight(); } public function __toString() { return "i m a rectangle... my area is ".$this->area(); } } $obA = new Circle(3); $obB = $obA->duplicate(); echo $obB; ?> 09/15/11 (c) 2011 Haim Michael. All Rights Reserved. 37