SlideShare a Scribd company logo
1 of 27
Download to read offline
Design Patterns


               Lorna Mitchell
           PHP East Midlands
               3 March 2011
                  rd
Design Patterns
●
    Common language
●
    Familiar problems
●
    NOT rocket science or the holy grail
Some Common Patterns
●
    Singleton
●
    Registry
●
    Factory
●
    Adapter
●
    Decorator
●
    Observer
Singleton
●
    Only one object of this type can exist
●
    Private constructor
●
    Method to return the object
●
    Class manages instantiation
Singleton Example
   1   <?php
   2
   3   class Singleton
   4   {
   5      private static $classInstance;
   6
   7       private function __construct () {}
   8
   9       static function getInstance () {
  10          if (! isset(self::$classInstance)) {
  11             self::$classInstance = new Singleton();
  12          }
  13          return (self::$   classInstance);
  14       }
  15   }
Singleton Is Uncool
●
    Hard to test
●
    Dependency injection is better
●
    Terribly unfashionable
●
    Better than a global variable
Registry
●
    A singleton of singletons
●
    Zend_Registry is an example
●
    Can instantiate, or just store
Registry Example
 1 class Registry
 2 {
 3     private static $storage;
 4
 5     private function __construct () {}
 6
 7     public function set($key, $value) {
 8         self::$storage[$key] = $value;
 9     }
10
11     public function get($key) {
12         if(array_key_exists($key, self::$storage)) {
13              return self::$storage[$key];
14         } else {
15              return false;
16         }
17     }
             19
18 }
             20 Registry::set('shinyThing', new StdClass());
             21 // later ...
             22 $shiny = Registry::get('shinyThing');
Factory
●
    Logic involved in creating an object
●
    Objects usually related
●
    Helpful for testing
Factory Example
  1   class WidgetFactory
  2   {
  3      public function getWiget($type) {
  4        switch($type) {
  5          case 'DatePicker':
  6            // assume simple look/feel, use $options
  7            return new SimpleDatePicker($options);
  8            break;
  9          default:
 10            // do nothing, invalid widget type
 11            break;
 12        }
 13      }
 14   }
 15
 16   $widget_factory = new WidgetFactory();
 17   $picker = $widget_factory->getWidget('DatePicker');
 18   $picker->render();
Combining Patterns
●
    A singleton is also a factory
●
    Can combine factory and registry
Adapter
●
    Making one object look like another
●
    Adapter class presents one interface, and may
    map to another
●
    Target class left unchanged
●
    PDO is a great example
Adapter Example
  1   <?php
  2
  3   class User {
  4       function getUsername() {
  5           return "joe";
  6       }
  7
  8       function getId() {
  9           return 42;
 10       }
 11
 12       function isValid($username, $password) {
 13           return true;
 14       }
 15   }
 16
 17   $user = new User();
 18   if($user->isValid('joe','secret')) {
 19       echo 'Hi ' . $user->getUsername();
 20   }
Adapter Example
  1 <?php
  2
  3 class SuperDuperUser {
  4     function getUser() {
  5         return array ("username" => "joe",
                 "id" => 42);
  6     }
  7
  8     function areCredentialsOK($usr, $pass) {
  9         return true;
 10     }
 11 }
Adapter Example
13   class UserAdapter {
14     function __construct() {
15       $this->_original = new SuperDuperUser();
16     }
18     function getUsername() {
19       $user = $this->_original->getUser();
20       return $user['username'];
21     }
22     function getId() {
23       $user = $this->_original->getUser();
24       return $user['id'];
25     }
27     function isValid($username, $password) {
28       return $this->_original->areCredentialsOK($usr,$pass);
29     }
30   }
31
32   $user = new UserAdapter();
33   if($user->isValid('joe','secret')) {
34       echo 'Hi ' . $user->getUsername();
35   }
Decorator
●
    Unintrusive
●
    Object encloses another object
    ●
        think of pass-the-parcel!
●
    Often literally for visual decoration
Decorator Example
 1   <?php
 2
 3   Interface WeatherInterface {
 4       public function getWeather();
 5   }
 6
 7   class WeatherBot implements WeatherInterface {
 8       public function getWeather() {
 9           // imagine something more complicated
10           return 'Sunny';
11       }
12   }
13
Decorator Example
14   class WordyDecorator implements WeatherInterface
15   {
16     protected $weatherInterface;
18     public function __construct (WeatherInterface $weather) {
19       $this->weatherInterface = $weather;
20     }
22     public function getWeather () {
23       $string = 'Today: '.$this->weatherInterface->getWeather();
24       return ($string);
25     }
26   }
27
28   class BorderDecorator implements WeatherInterface
29   {
30     protected $weatherInterface;
32     public function __construct (WeatherInterface $weather) {
33       $this->weatherInterface = $weather;
34     }
36     public function getWeather () {
37       $string = '~{'.$this->weatherInterface->getWeather().'}~';
38       return ($string);
39     }
40   }
Decorator Example


42 $weather = new WordyDecorator(new WeatherBot);
43 echo $weather->getWeather();
44
Observer
●
    Both subject and object know about the pattern
●
    Observer requests updates
●
    Observee notifies everyone on change
●
    Also called publish/subscribe
Observer Example

                   Target


                      Notify
   Register
   Interest


      Observer
Observer Example
 1 class BankAccount
 2 {
 3    protected $amount;
 4    protected $observer;
 5    public function __construct ($amount) {
 6       $this->observer = new MoneyObserver();
 7       $this->setAmount($amount);
 8    }
 9    protected function setAmount ($amount) {
10       $this->amount = $amount;
11       $this->notify();
12    }
13    public function deposit ($money) {
14       $this->setAmount($this->amount + $money);
15    }
16    public function withdraw ($money) {
17       $this->setAmount($this->amount - $money);
18    }
19    public function notify () {
20       $this->observer->update($this);
21    }
22 }
Observer Example

24 class MoneyObserver
25 {
26    public function update (BankAccount $act) {
27      echo date('H:i:s.u') . ': Balance change: &pound;'
28         . $act->balance() . '<br />';
29    }
30 }
Design Patterns
●
    Singleton
●
    Registry
●
    Factory
●
    Adapter
●
    Decorator
●
    Observer
●
    ... and many more!
Design Patterns
●
    Common vocabulary
●
    NOT a silver bullet
●
    Another tool in the box
●
    Remember: All things in moderation!
Resources
●
    “Gang Of Four” book: Design Patterns:
    Elements of Reusable Object-Oriented
    Software
    ●
        Gamma, Helm, Johnson, Vlissides
●
    Patterns of Enterprise Application Architecture
    ●
        Fowler
●
    http://www.fluffycat.com/PHP-Design-Patterns/
Questions?

More Related Content

What's hot

Combatendo code smells em Java
Combatendo code smells em Java Combatendo code smells em Java
Combatendo code smells em Java Emmanuel Neri
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
Doctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkDoctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkAndrew Yatsenko
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceAnanda Kumar HN
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Kim Hunmin
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019julien pauli
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)Ananda Kumar HN
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsClinton Dreisbach
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilorRazvan Raducanu, PhD
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQueryPhDBrown
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulDavid Engel
 
10 tips for a reusable architecture
10 tips for a reusable architecture10 tips for a reusable architecture
10 tips for a reusable architectureJorge Ortiz
 

What's hot (20)

Combatendo code smells em Java
Combatendo code smells em Java Combatendo code smells em Java
Combatendo code smells em Java
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
Doctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWorkDoctrine Internals. UnitOfWork
Doctrine Internals. UnitOfWork
 
C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit Inheritance
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
Grails UI Primer
Grails UI PrimerGrails UI Primer
Grails UI Primer
 
ES2015 New Features
ES2015 New FeaturesES2015 New Features
ES2015 New Features
 
Symfony2 your way
Symfony2   your waySymfony2   your way
Symfony2 your way
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
 
10 tips for a reusable architecture
10 tips for a reusable architecture10 tips for a reusable architecture
10 tips for a reusable architecture
 

Similar to Design Patterns

The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHPSharon Levy
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesThomas Weinert
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injectionJosh Adell
 
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
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
 
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSLPHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSLiMasters
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)Arnaud Langlade
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICKonstantin Kudryashov
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service ManagerChris Tankersley
 
Desymfony2013.gonzalo123
Desymfony2013.gonzalo123Desymfony2013.gonzalo123
Desymfony2013.gonzalo123Gonzalo Ayuso
 

Similar to Design Patterns (20)

The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHP
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard Interfaces
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
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...
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSLPHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
What is DDD and how could it help you
What is DDD and how could it help youWhat is DDD and how could it help you
What is DDD and how could it help you
 
What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service Manager
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 
Desymfony2013.gonzalo123
Desymfony2013.gonzalo123Desymfony2013.gonzalo123
Desymfony2013.gonzalo123
 

More from Lorna Mitchell

Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API DesignLorna Mitchell
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open SourceLorna Mitchell
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyLorna Mitchell
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knewLorna Mitchell
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Lorna Mitchell
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP StackLorna Mitchell
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source ControlLorna Mitchell
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service DesignLorna Mitchell
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishLorna Mitchell
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHPLorna Mitchell
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?Lorna Mitchell
 

More from Lorna Mitchell (20)

OAuth: Trust Issues
OAuth: Trust IssuesOAuth: Trust Issues
OAuth: Trust Issues
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Best Practice in API Design
Best Practice in API DesignBest Practice in API Design
Best Practice in API Design
 
Git, GitHub and Open Source
Git, GitHub and Open SourceGit, GitHub and Open Source
Git, GitHub and Open Source
 
Business 101 for Developers: Time and Money
Business 101 for Developers: Time and MoneyBusiness 101 for Developers: Time and Money
Business 101 for Developers: Time and Money
 
Things I wish web graduates knew
Things I wish web graduates knewThings I wish web graduates knew
Things I wish web graduates knew
 
Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)Teach a Man To Fish (phpconpl edition)
Teach a Man To Fish (phpconpl edition)
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Join In With Joind.In
Join In With Joind.InJoin In With Joind.In
Join In With Joind.In
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
 
Going Freelance
Going FreelanceGoing Freelance
Going Freelance
 
Understanding Distributed Source Control
Understanding Distributed Source ControlUnderstanding Distributed Source Control
Understanding Distributed Source Control
 
Best Practice in Web Service Design
Best Practice in Web Service DesignBest Practice in Web Service Design
Best Practice in Web Service Design
 
Coaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To FishCoaching Development Teams: Teach A Man To Fish
Coaching Development Teams: Teach A Man To Fish
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Implementing OAuth with PHP
Implementing OAuth with PHPImplementing OAuth with PHP
Implementing OAuth with PHP
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Example Presentation
Example PresentationExample Presentation
Example Presentation
 
Could You Telecommute?
Could You Telecommute?Could You Telecommute?
Could You Telecommute?
 

Recently uploaded

Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiRaviKumarDaparthi
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxMasterG
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 

Recently uploaded (20)

Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi Daparthi
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 

Design Patterns

  • 1. Design Patterns Lorna Mitchell PHP East Midlands 3 March 2011 rd
  • 2. Design Patterns ● Common language ● Familiar problems ● NOT rocket science or the holy grail
  • 3. Some Common Patterns ● Singleton ● Registry ● Factory ● Adapter ● Decorator ● Observer
  • 4. Singleton ● Only one object of this type can exist ● Private constructor ● Method to return the object ● Class manages instantiation
  • 5. Singleton Example 1 <?php 2 3 class Singleton 4 { 5 private static $classInstance; 6 7 private function __construct () {} 8 9 static function getInstance () { 10 if (! isset(self::$classInstance)) { 11 self::$classInstance = new Singleton(); 12 } 13 return (self::$ classInstance); 14 } 15 }
  • 6. Singleton Is Uncool ● Hard to test ● Dependency injection is better ● Terribly unfashionable ● Better than a global variable
  • 7. Registry ● A singleton of singletons ● Zend_Registry is an example ● Can instantiate, or just store
  • 8. Registry Example 1 class Registry 2 { 3 private static $storage; 4 5 private function __construct () {} 6 7 public function set($key, $value) { 8 self::$storage[$key] = $value; 9 } 10 11 public function get($key) { 12 if(array_key_exists($key, self::$storage)) { 13 return self::$storage[$key]; 14 } else { 15 return false; 16 } 17 } 19 18 } 20 Registry::set('shinyThing', new StdClass()); 21 // later ... 22 $shiny = Registry::get('shinyThing');
  • 9. Factory ● Logic involved in creating an object ● Objects usually related ● Helpful for testing
  • 10. Factory Example 1 class WidgetFactory 2 { 3 public function getWiget($type) { 4 switch($type) { 5 case 'DatePicker': 6 // assume simple look/feel, use $options 7 return new SimpleDatePicker($options); 8 break; 9 default: 10 // do nothing, invalid widget type 11 break; 12 } 13 } 14 } 15 16 $widget_factory = new WidgetFactory(); 17 $picker = $widget_factory->getWidget('DatePicker'); 18 $picker->render();
  • 11. Combining Patterns ● A singleton is also a factory ● Can combine factory and registry
  • 12. Adapter ● Making one object look like another ● Adapter class presents one interface, and may map to another ● Target class left unchanged ● PDO is a great example
  • 13. Adapter Example 1 <?php 2 3 class User { 4 function getUsername() { 5 return "joe"; 6 } 7 8 function getId() { 9 return 42; 10 } 11 12 function isValid($username, $password) { 13 return true; 14 } 15 } 16 17 $user = new User(); 18 if($user->isValid('joe','secret')) { 19 echo 'Hi ' . $user->getUsername(); 20 }
  • 14. Adapter Example 1 <?php 2 3 class SuperDuperUser { 4 function getUser() { 5 return array ("username" => "joe", "id" => 42); 6 } 7 8 function areCredentialsOK($usr, $pass) { 9 return true; 10 } 11 }
  • 15. Adapter Example 13 class UserAdapter { 14 function __construct() { 15 $this->_original = new SuperDuperUser(); 16 } 18 function getUsername() { 19 $user = $this->_original->getUser(); 20 return $user['username']; 21 } 22 function getId() { 23 $user = $this->_original->getUser(); 24 return $user['id']; 25 } 27 function isValid($username, $password) { 28 return $this->_original->areCredentialsOK($usr,$pass); 29 } 30 } 31 32 $user = new UserAdapter(); 33 if($user->isValid('joe','secret')) { 34 echo 'Hi ' . $user->getUsername(); 35 }
  • 16. Decorator ● Unintrusive ● Object encloses another object ● think of pass-the-parcel! ● Often literally for visual decoration
  • 17. Decorator Example 1 <?php 2 3 Interface WeatherInterface { 4 public function getWeather(); 5 } 6 7 class WeatherBot implements WeatherInterface { 8 public function getWeather() { 9 // imagine something more complicated 10 return 'Sunny'; 11 } 12 } 13
  • 18. Decorator Example 14 class WordyDecorator implements WeatherInterface 15 { 16 protected $weatherInterface; 18 public function __construct (WeatherInterface $weather) { 19 $this->weatherInterface = $weather; 20 } 22 public function getWeather () { 23 $string = 'Today: '.$this->weatherInterface->getWeather(); 24 return ($string); 25 } 26 } 27 28 class BorderDecorator implements WeatherInterface 29 { 30 protected $weatherInterface; 32 public function __construct (WeatherInterface $weather) { 33 $this->weatherInterface = $weather; 34 } 36 public function getWeather () { 37 $string = '~{'.$this->weatherInterface->getWeather().'}~'; 38 return ($string); 39 } 40 }
  • 19. Decorator Example 42 $weather = new WordyDecorator(new WeatherBot); 43 echo $weather->getWeather(); 44
  • 20. Observer ● Both subject and object know about the pattern ● Observer requests updates ● Observee notifies everyone on change ● Also called publish/subscribe
  • 21. Observer Example Target Notify Register Interest Observer
  • 22. Observer Example 1 class BankAccount 2 { 3 protected $amount; 4 protected $observer; 5 public function __construct ($amount) { 6 $this->observer = new MoneyObserver(); 7 $this->setAmount($amount); 8 } 9 protected function setAmount ($amount) { 10 $this->amount = $amount; 11 $this->notify(); 12 } 13 public function deposit ($money) { 14 $this->setAmount($this->amount + $money); 15 } 16 public function withdraw ($money) { 17 $this->setAmount($this->amount - $money); 18 } 19 public function notify () { 20 $this->observer->update($this); 21 } 22 }
  • 23. Observer Example 24 class MoneyObserver 25 { 26 public function update (BankAccount $act) { 27 echo date('H:i:s.u') . ': Balance change: &pound;' 28 . $act->balance() . '<br />'; 29 } 30 }
  • 24. Design Patterns ● Singleton ● Registry ● Factory ● Adapter ● Decorator ● Observer ● ... and many more!
  • 25. Design Patterns ● Common vocabulary ● NOT a silver bullet ● Another tool in the box ● Remember: All things in moderation!
  • 26. Resources ● “Gang Of Four” book: Design Patterns: Elements of Reusable Object-Oriented Software ● Gamma, Helm, Johnson, Vlissides ● Patterns of Enterprise Application Architecture ● Fowler ● http://www.fluffycat.com/PHP-Design-Patterns/