SlideShare a Scribd company logo
Object Oriented Design Patterns for PHP <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> An introduction of sorts into the world of design patterns for object oriented PHP, as brought to you by Robert Gonzalez. http://www.robert-gonzalez.com [email_address] http://www.robert-gonzalez.com/personal/meetups/apache-49-20081218-code.tar.gz http://www.robert-gonzalez.com/personal/meetups/apache-49-20081218-presentation.odp http://www.slideshare.net/RobertGonzalez/object-oriented-design-patterns-for-php-presentation/
Object Oriented Design Patterns for PHP Who is this Robert dude? What are design patterns? How can design patterns help you? <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> $this->setup();
Object Oriented Design Patterns for PHP Who is this Robert dude? Husband and father Web developer Self taught Began learning HTML in 1997 Began learning Perl in 2000 Began learning PHP in 2003 Full time developer for Bay Alarm Company since 2006 PHP freak Administrator of the PHP Developers Network forums Frequent contributor to Professional PHP Google group Chief helper of n00Bs (at work and beyond) Zend Certified PHP 5 Engineer Awesome barbecuer <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP What are design patterns? The words ”Object Oriented Design” repeated on wall paper An industry buzzword that gets you into meetups Recurring solutions to common software development challenges Mind bending algorithms of confusion and indigestion The words ”Object Oriented Design” repeated on wall paper An industry buzzword that gets you into meetups Recurring solutions to common software development challenges Mind bending algorithms of confusion and indigestion <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP What are design patterns  not ? They are not the end all, be all to all of your coding challenges. They are not a requirement of object oriented programming. They are not a requirement of good programming. They are not a substitute for application code and logic. They are not always the best solution for the job. They are not always the easiest concept to grasp and/or use. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Some common software development challenges: Building new applications while leveraging existing codebases Building/enhancing applications securely, quickly and effectively Integrating new and existing applications Multiple developers programming the same product Few developers programming many products Varying, sometimes unknown, data sources Varying, sometimes unknown, operating systems Varying, sometimes unknown, platforms and setups <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Yeah, this is all well and good. And your presentation so far kicks all kinds of ass, but seriously, what are design patterns really going to do for me? Let's have a look at some patterns and see ... <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Lazy Load Pattern Lazy loading is the process of delaying the instantiation of an object until the instance is needed. We all know the mantra, lazy programmers are the best programmers. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Lazy Load Pattern <?php  /**   * Sample class   */  class  MyClass  {       /**       * Holder for the SomeObject object       *        * @access protected       * @var SomeObject       */       protected  $_myobject  =  null ;             /**       * Get the instance of SomeObject, but only when we need it       *        * @access public       * @return SomeObject       */       public function  fetchObject () {          if ( $this -> _myobject  ===  null ) {               $this -> _myobject  = new  SomeObject ;          }                    return  $this -> _myobject ;      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Why the Lazy Load rocks: Delays resource consumption until it is needed, which may be never Is relatively easy to understand Offers an encapsulated means of creating objects Offers an encapsulated means of storing objects for use later <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> Did you just see that? Did he just say storing objects for use later?
Object Oriented Design Patterns for PHP The Registry Pattern A registry is an object that other objects can use to access data, settings, values and other objects from a sort of internal storehouse. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Registry Pattern <?php  /**   * Class that manages registry entries for an application.   */   class  Registry  {       /**       * Holds the registry labels and values data       */                               protected static  $_register  = array();             /**       * Sets a value into the registry if there is no value with this label already       */                               public static function  set ( $label ,  $value ) {          if (!isset( self :: $_register [ $label ])) {               self :: $_register [ $label ] =  $value ;          }      }             /**       * Gets a value from the registry if there is a label with this value       */                               public static function  get ( $label ) {          if (isset( self :: $_register [ $label ]) {              return  self :: $_register [ $label ];          }      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Common uses of a Registry: Maintaining values throughout a request Setting/getting configuration values Allowing access to variables within an application without globals For Windows user, causing hours and hours of grief when corrupt <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> Can you think of a feature/extension of PHP that uses a sort of registry pattern? Is there way to instantiate the Registry Pattern but force only a single instance of it?
Object Oriented Design Patterns for PHP The Singleton Pattern The singleton patterns ensures that one and only one instance of an object exists. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Singleton Pattern <?php  /**   * Class that only ever has one instance of itself floating around.   */   class  Singleton  {       /**       * Holds the instance of itself in this property       */                               private static  $_instance  =  null ;             /**       * Final and private constructor means this can only be instantiated from within       */                               final private function  __construct () {}             /**       * Gets the single instance of this object        */                               public static function  getInstance () {          if ( self :: $_instance  ===  null ) {               self :: $_instance  = new  self ;          }                    return  self :: $_instance ;      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Pros and cons of the Singleton: Pro: You know you have the same instance available at all times. Con: One and only one instance is all you get. Pro: Instantiates itself for you so all you need to do is get it. Con: Autoinstantiation diminishes flexibility of argument passing. Pro: Since it is singleton it can replace global variable declaration. Con: Since it is singleton it can replace global variable declaration. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> What are some situations of a developer needing one and only one instance of an object?
Object Oriented Design Patterns for PHP The Factory Method Pattern The factory method is a method whose sole purpose in life is to create objects. Most commonly (and really per definition) the factory method is an interface method that delegates object instantiation decisions to subclasses. However, it also commonly acceptable to say that a method that creates objects (both of known and unknown classes) is a factory method. PLEASE NOTE: The factory method pattern is not the same as the factory pattern, which we will NOT be covering in this presentation. <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Factory Method Pattern <?php  /**   * A factory method implementation   */  abstract class  Creator  {       /**       * Abstract factory method to be defined by child classes       */       abstract public function  createObject ( $type );  }  class  ConcreteCreatorA  extends  Creator  {      public function  createObject ( $type ) {          switch ( $type ) {               // Handle cases for concrete classes           }      }  }  class  ConcreteCreatorB  extends  Creator  {      public function  createObject ( $type ) {          switch ( $type ) {               // Handle cases for concrete classes           }      }  }  $b  = new  ConcreteCreatorB ;  $b -> create ( 'ConcreteProductB' );   <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Factory Method Pattern, an alternative <?php  /**   * A little class to handle creation of objects   */  class  Lib_Factory  {       /**       * Create an object of type $name       */       public static function  createObject ( $name ,  $args  = array()) {           /**            * Move our class name into a file path, turning names like           * App_Db_Handler into something like App/Db/Handler.php           */           $file  =  str_replace ( '_' ,  PATH_SEPARATOR ,  $name ) .  '.php' ;                     // Get the file           if ( file_exists ( $file )) {              require_once  $file ;               $obj  = new  $name ( $args );              return  $obj ;          }                    // Throw an exception if we get here         throw new  Exception ( &quot;The class name $name could not be instantiated.&quot; );      }  }   <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Factory Method Pattern benefits: Encapsulates object creation Allows a range of functionality for error trapping, loading, etc Does not need to know anything about what it is creating Easy to read, easy to understand Lightweight, fast and can be made into a static method <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> Is there a way to tie all these patterns together  into something usable? I think we can, but first...
Object Oriented Design Patterns for PHP The Strategy Pattern The strategy pattern defines and encapsulates a set of algorithms and makes them interchangeable, allowing the algorithms to vary independent from the objects that use them. Uh, what? <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern Encapsulates what changes and leaves what doesn't change alone Makes encapsulated algorithms interchangeable Favors composition over inheritance <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> With some patterns, like the Strategy Pattern, the best way to ”get” it is to see it. Let's have a look...
Object Oriented Design Patterns for PHP The Strategy Pattern, part 1 <?php  abstract class  Computer  {      public  $type ;      public  $platform ;            abstract public function  identify ();            public function  transport () {           $this -> type -> transport ();      }            public function  openTerminal () {           $this -> platform -> terminal ();      }            public function  closeTerminal () {          echo  &quot;Close the terminal: type e-x-i-t, hit <enter>&quot; ;      }            public function  setComputerType ( ComputerType $type ) {           $this -> type  =  $type ;      }            public function  setPlatform ( ComputerPlatform $platform ) {           $this -> platform  =  $platform ;      }            public function  gotoNext () { echo  &quot;Moving on...&quot; ; }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, part 2 <?php  interface  ComputerType  {      public function  transport ();  }  class  ComputerType_Laptop  implements  ComputerType  {      public function  transport () {          echo  &quot;Transporting... Put the laptop in the bag and no one gets hurt.&quot; ;      }  }  class  ComputerType_Desktop  implements  ComputerType  {      public function  transport () {          echo  &quot;Transporting... Get the boxes, load it up, move it.&quot; ;      }  }  class  ComputerType_Server  implements  ComputerType  {      public function  transport () {          echo  &quot;Transporting... Seriously? Yeah, right. Transport this!&quot; ;      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, part 3 <?php  interface  ComputerPlatform  {      public function  terminal ();  }  class  ComputerPlatform_Mac  implements  ComputerPlatform  {      public function  terminal () {          echo  &quot;Open the terminal: Go to applications -> terminal.&quot; ;      }  }  class  ComputerPlatform_Ubuntu  implements  ComputerPlatform  {      public function  terminal () {          echo  &quot;Open the terminal: Go to applications -> accessories -> terminal.&quot; ;      }  }  class  ComputerPlatform_Windows  implements  ComputerPlatform  {      public function  terminal () {          echo  &quot;Open the terminal: I am not smart enough to have a terminal but ...&quot; ;      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, part 4 <?php  class  Computer_Mac  extends  Computer  {      public function  __construct () {           $this -> type  = new  ComputerType_Laptop ;           $this -> platform  = new  ComputerPlatform_Mac ;      }            public function  identify () {          echo  &quot;I am a mac.&quot; ;      }  }  class  Computer_PC  extends  Computer  {      public function  __construct () {           $this -> type  = new  ComputerType_Desktop ;           $this -> platform  = new  ComputerPlatform_Windows ;      }            public function  identify () {          echo  &quot;I'm a PC (or is that POS?).&quot; ;      }  }  <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, part 4 continued <?php  class  Computer_Server  extends  Computer  {      public function  __construct () {           $this -> type  = new  ComputerType_Server ;           $this -> platform  = new  ComputerPlatform_Ubuntu ;      }            public function  identify () {          echo  &quot;I am Ubuntu, one of a multitude of flavors of linux.&quot; ;      }  } <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, part 5 <?php  class  Computer_Identifier  {      public function  __construct () {           $mac  = new  Computer_Mac ;           $mac -> identify ();           $mac -> openTerminal ();           $mac -> closeTerminal ();           $mac -> gotoNext ();           $pc  = new  Computer_PC ;           $pc -> identify ();           $pc -> openTerminal ();           $pc -> closeTerminal ();           $pc -> gotoNext ();           $linux  = new  Computer_Server ;           $linux -> identify ();           $linux -> transport ();      }  } $comps  = new  Computer_Identifier ; <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP The Strategy Pattern, in action I am a mac. Open the terminal: Go to applications -> terminal. Close the terminal: type e-x-i-t, hit <enter> Moving on... I'm a PC (or is that POS?). Open the terminal: I am not smart enough to have a terminal but you can go to start -> all programs -> accessories -> command prompt. Close the terminal: type e-x-i-t, hit <enter> Moving on... I am Ubuntu, one of a multitude of flavors of linux. Transporting... Seriously? Yeah, right. Transport this! <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP Notes about the Strategy Pattern Probably one of the most common patterns in OOP One of the most powerful patterns in development Opens a wealth of possibility when understood Very flexible when favoring composition over inheritance Encapsulates what changes to allow for greater extendability <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?>
Object Oriented Design Patterns for PHP <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> Knowing what we know now, can you think of how these patterns can be applied to your applications to make for faster, more robust and cleaner application code? Maybe we can look at some code...
Object Oriented Design Patterns for PHP <?php   if  ( $this ->try && ! $this ->succeed())  $this ->try++;  /* Robert Gonzalez, 2008-12-18 */   ?> Design patterns are a great way to modularize your code and create reusable structures. But they mean nothing if they go unused. Go code something. Much more information about design patterns, reusable code and object oriented programming can be found by simply typing those keywords into the Google search box :) http://www.robert-gonzalez.com [email_address]

More Related Content

What's hot

Getting modern with logging via log4perl
Getting modern with logging via log4perlGetting modern with logging via log4perl
Getting modern with logging via log4perl
Dean Hamstead
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
Dean Hamstead
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
Nyros Technologies
 
C:\Users\User\Desktop\Eclipse Infocenter
C:\Users\User\Desktop\Eclipse InfocenterC:\Users\User\Desktop\Eclipse Infocenter
C:\Users\User\Desktop\Eclipse Infocenter
Suite Solutions
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
tutorialsruby
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Yi-Huan Chan
 
2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
terry chay
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
Suite Solutions
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
Dmitry Buzdin
 
Survey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a ChatbotSurvey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a Chatbot
Nguyen Giang
 
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
Stephan Schmidt
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
danwrong
 
PHP Annotations: They exist! - JetBrains Webinar
 PHP Annotations: They exist! - JetBrains Webinar PHP Annotations: They exist! - JetBrains Webinar
PHP Annotations: They exist! - JetBrains Webinar
Rafael Dohms
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
Stephen Colebourne
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
Dr. Syed Hassan Amin
 

What's hot (19)

Getting modern with logging via log4perl
Getting modern with logging via log4perlGetting modern with logging via log4perl
Getting modern with logging via log4perl
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
 
Oops in PHP By Nyros Developer
Oops in PHP By Nyros DeveloperOops in PHP By Nyros Developer
Oops in PHP By Nyros Developer
 
C:\Users\User\Desktop\Eclipse Infocenter
C:\Users\User\Desktop\Eclipse InfocenterC:\Users\User\Desktop\Eclipse Infocenter
C:\Users\User\Desktop\Eclipse Infocenter
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
php_tizag_tutorial
php_tizag_tutorialphp_tizag_tutorial
php_tizag_tutorial
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
2009-02 Oops!
2009-02 Oops!2009-02 Oops!
2009-02 Oops!
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Survey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a ChatbotSurvey on Script-based languages to write a Chatbot
Survey on Script-based languages to write a Chatbot
 
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
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
PHP Annotations: They exist! - JetBrains Webinar
 PHP Annotations: They exist! - JetBrains Webinar PHP Annotations: They exist! - JetBrains Webinar
PHP Annotations: They exist! - JetBrains Webinar
 
Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 

Viewers also liked

Design patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMDesign patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAM
Nishant Shrivastava
 
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
Fabien Potencier
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Bradley Holt
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
Bruno Pedro
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
David Stockton
 
Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012
Aaron Saray
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
Rob Knight
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
Sudarsun Santhiappan
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
Damien Seguy
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
Mindfire Solutions
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
Vibrant Technologies & Computers
 
Best Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle DatabaseBest Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle Database
Christopher Jones
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
iimjobs and hirist
 
HTML5 for PHP Developers - IPC
HTML5 for PHP Developers - IPCHTML5 for PHP Developers - IPC
HTML5 for PHP Developers - IPC
Mayflower GmbH
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
Lorna Mitchell
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php Presentation
Php PresentationPhp Presentation
Php Presentation
Manish Bothra
 
Laravel 5 and SOLID
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLID
Igor Talevski
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
Jonathan Simon
 
Unt 3 attributes, methods, relationships-1
Unt 3 attributes, methods, relationships-1Unt 3 attributes, methods, relationships-1
Unt 3 attributes, methods, relationships-1
gopal10scs185
 

Viewers also liked (20)

Design patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMDesign patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAM
 
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
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
PHP and Web Services
PHP and Web ServicesPHP and Web Services
PHP and Web Services
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
 
Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012Your first 5 PHP design patterns - ThatConference 2012
Your first 5 PHP design patterns - ThatConference 2012
 
Object Relational Mapping in PHP
Object Relational Mapping in PHPObject Relational Mapping in PHP
Object Relational Mapping in PHP
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
Best Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle DatabaseBest Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle Database
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
 
HTML5 for PHP Developers - IPC
HTML5 for PHP Developers - IPCHTML5 for PHP Developers - IPC
HTML5 for PHP Developers - IPC
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Laravel 5 and SOLID
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLID
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Unt 3 attributes, methods, relationships-1
Unt 3 attributes, methods, relationships-1Unt 3 attributes, methods, relationships-1
Unt 3 attributes, methods, relationships-1
 

Similar to Object Oriented Design Patterns for PHP

Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Nguyen Duc Phu
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
Dinh Pham
 
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
 
Hardcore PHP
Hardcore PHPHardcore PHP
Hardcore PHP
Roberto Luis Bisbé
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
Richard McIntyre
 
WordPress Development Confoo 2010
WordPress Development Confoo 2010WordPress Development Confoo 2010
WordPress Development Confoo 2010
Brendan Sera-Shriar
 
Passing The Joel Test In The PHP World
Passing The Joel Test In The PHP WorldPassing The Joel Test In The PHP World
Passing The Joel Test In The PHP World
Lorna Mitchell
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
GeeksLab Odessa
 
Python分享
Python分享Python分享
Python分享
fangdeng
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
The Basics Of Page Creation
The Basics Of Page CreationThe Basics Of Page Creation
The Basics Of Page Creation
Wildan Maulana
 
Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)
Michiel Rook
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
HamletDRC
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)
Oleg Zinchenko
 
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Steven Pignataro
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
Darwin Biler
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend Expressive
Milad Arabi
 
Open Power Template 2 presentation
Open Power Template 2 presentationOpen Power Template 2 presentation
Open Power Template 2 presentation
Tomasz Jędrzejewski
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
Lakshman Prasad
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development
Fitz Agard
 

Similar to Object Oriented Design Patterns for PHP (20)

Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
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)
 
Hardcore PHP
Hardcore PHPHardcore PHP
Hardcore PHP
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
WordPress Development Confoo 2010
WordPress Development Confoo 2010WordPress Development Confoo 2010
WordPress Development Confoo 2010
 
Passing The Joel Test In The PHP World
Passing The Joel Test In The PHP WorldPassing The Joel Test In The PHP World
Passing The Joel Test In The PHP World
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
 
Python分享
Python分享Python分享
Python分享
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
The Basics Of Page Creation
The Basics Of Page CreationThe Basics Of Page Creation
The Basics Of Page Creation
 
Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)
 
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend Expressive
 
Open Power Template 2 presentation
Open Power Template 2 presentationOpen Power Template 2 presentation
Open Power Template 2 presentation
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
 
Mongo NYC PHP Development
Mongo NYC PHP Development Mongo NYC PHP Development
Mongo NYC PHP Development
 

Recently uploaded

What's New in Teams Calling, Meetings, Devices June 2024
What's New in Teams Calling, Meetings, Devices June 2024What's New in Teams Calling, Meetings, Devices June 2024
What's New in Teams Calling, Meetings, Devices June 2024
Stephanie Beckett
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Nicolás Lopéz
 
NVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space ExplorationNVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space Exploration
Alison B. Lowndes
 
Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
Priyanka Aash
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
shyamraj55
 
Retrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with RagasRetrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with Ragas
Zilliz
 
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
FIDO Alliance
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
SelfMade bd
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
Keynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive SecurityKeynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive Security
Priyanka Aash
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
KIRAN KV
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
Zilliz
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
Priyanka Aash
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
FIDO Alliance
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
shanihomely
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
siddu769252
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
isBullShit
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
alexjohnson7307
 

Recently uploaded (20)

What's New in Teams Calling, Meetings, Devices June 2024
What's New in Teams Calling, Meetings, Devices June 2024What's New in Teams Calling, Meetings, Devices June 2024
What's New in Teams Calling, Meetings, Devices June 2024
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
 
NVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space ExplorationNVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space Exploration
 
Redefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI CapabilitiesRedefining Cybersecurity with AI Capabilities
Redefining Cybersecurity with AI Capabilities
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
 
Retrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with RagasRetrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with Ragas
 
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
UX Webinar Series: Drive Revenue and Decrease Costs with Passkeys for Consume...
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
Keynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive SecurityKeynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive Security
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
Accelerating Migrations = Recommendations
Accelerating Migrations = RecommendationsAccelerating Migrations = Recommendations
Accelerating Migrations = Recommendations
 
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
leewayhertz.com-Generative AI tech stack Frameworks infrastructure models and...
 

Object Oriented Design Patterns for PHP

  • 1. Object Oriented Design Patterns for PHP <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> An introduction of sorts into the world of design patterns for object oriented PHP, as brought to you by Robert Gonzalez. http://www.robert-gonzalez.com [email_address] http://www.robert-gonzalez.com/personal/meetups/apache-49-20081218-code.tar.gz http://www.robert-gonzalez.com/personal/meetups/apache-49-20081218-presentation.odp http://www.slideshare.net/RobertGonzalez/object-oriented-design-patterns-for-php-presentation/
  • 2. Object Oriented Design Patterns for PHP Who is this Robert dude? What are design patterns? How can design patterns help you? <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> $this->setup();
  • 3. Object Oriented Design Patterns for PHP Who is this Robert dude? Husband and father Web developer Self taught Began learning HTML in 1997 Began learning Perl in 2000 Began learning PHP in 2003 Full time developer for Bay Alarm Company since 2006 PHP freak Administrator of the PHP Developers Network forums Frequent contributor to Professional PHP Google group Chief helper of n00Bs (at work and beyond) Zend Certified PHP 5 Engineer Awesome barbecuer <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 4. Object Oriented Design Patterns for PHP What are design patterns? The words ”Object Oriented Design” repeated on wall paper An industry buzzword that gets you into meetups Recurring solutions to common software development challenges Mind bending algorithms of confusion and indigestion The words ”Object Oriented Design” repeated on wall paper An industry buzzword that gets you into meetups Recurring solutions to common software development challenges Mind bending algorithms of confusion and indigestion <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 5. Object Oriented Design Patterns for PHP What are design patterns not ? They are not the end all, be all to all of your coding challenges. They are not a requirement of object oriented programming. They are not a requirement of good programming. They are not a substitute for application code and logic. They are not always the best solution for the job. They are not always the easiest concept to grasp and/or use. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 6. Object Oriented Design Patterns for PHP Some common software development challenges: Building new applications while leveraging existing codebases Building/enhancing applications securely, quickly and effectively Integrating new and existing applications Multiple developers programming the same product Few developers programming many products Varying, sometimes unknown, data sources Varying, sometimes unknown, operating systems Varying, sometimes unknown, platforms and setups <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 7. Object Oriented Design Patterns for PHP Yeah, this is all well and good. And your presentation so far kicks all kinds of ass, but seriously, what are design patterns really going to do for me? Let's have a look at some patterns and see ... <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 8. Object Oriented Design Patterns for PHP The Lazy Load Pattern Lazy loading is the process of delaying the instantiation of an object until the instance is needed. We all know the mantra, lazy programmers are the best programmers. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 9. Object Oriented Design Patterns for PHP The Lazy Load Pattern <?php /**  * Sample class  */ class  MyClass  {      /**      * Holder for the SomeObject object      *       * @access protected      * @var SomeObject      */      protected  $_myobject  =  null ;           /**      * Get the instance of SomeObject, but only when we need it      *       * @access public      * @return SomeObject      */      public function  fetchObject () {         if ( $this -> _myobject  ===  null ) {              $this -> _myobject  = new  SomeObject ;         }                  return  $this -> _myobject ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 10. Object Oriented Design Patterns for PHP Why the Lazy Load rocks: Delays resource consumption until it is needed, which may be never Is relatively easy to understand Offers an encapsulated means of creating objects Offers an encapsulated means of storing objects for use later <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> Did you just see that? Did he just say storing objects for use later?
  • 11. Object Oriented Design Patterns for PHP The Registry Pattern A registry is an object that other objects can use to access data, settings, values and other objects from a sort of internal storehouse. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 12. Object Oriented Design Patterns for PHP The Registry Pattern <?php /**  * Class that manages registry entries for an application.  */  class  Registry  {      /**      * Holds the registry labels and values data      */                              protected static  $_register  = array();           /**      * Sets a value into the registry if there is no value with this label already      */                              public static function  set ( $label ,  $value ) {         if (!isset( self :: $_register [ $label ])) {              self :: $_register [ $label ] =  $value ;         }     }           /**      * Gets a value from the registry if there is a label with this value      */                              public static function  get ( $label ) {         if (isset( self :: $_register [ $label ]) {             return  self :: $_register [ $label ];         }     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 13. Object Oriented Design Patterns for PHP Common uses of a Registry: Maintaining values throughout a request Setting/getting configuration values Allowing access to variables within an application without globals For Windows user, causing hours and hours of grief when corrupt <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> Can you think of a feature/extension of PHP that uses a sort of registry pattern? Is there way to instantiate the Registry Pattern but force only a single instance of it?
  • 14. Object Oriented Design Patterns for PHP The Singleton Pattern The singleton patterns ensures that one and only one instance of an object exists. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 15. Object Oriented Design Patterns for PHP The Singleton Pattern <?php /**  * Class that only ever has one instance of itself floating around.  */  class  Singleton  {      /**      * Holds the instance of itself in this property      */                              private static  $_instance  =  null ;           /**      * Final and private constructor means this can only be instantiated from within      */                              final private function  __construct () {}           /**      * Gets the single instance of this object       */                              public static function  getInstance () {         if ( self :: $_instance  ===  null ) {              self :: $_instance  = new  self ;         }                  return  self :: $_instance ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 16. Object Oriented Design Patterns for PHP Pros and cons of the Singleton: Pro: You know you have the same instance available at all times. Con: One and only one instance is all you get. Pro: Instantiates itself for you so all you need to do is get it. Con: Autoinstantiation diminishes flexibility of argument passing. Pro: Since it is singleton it can replace global variable declaration. Con: Since it is singleton it can replace global variable declaration. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> What are some situations of a developer needing one and only one instance of an object?
  • 17. Object Oriented Design Patterns for PHP The Factory Method Pattern The factory method is a method whose sole purpose in life is to create objects. Most commonly (and really per definition) the factory method is an interface method that delegates object instantiation decisions to subclasses. However, it also commonly acceptable to say that a method that creates objects (both of known and unknown classes) is a factory method. PLEASE NOTE: The factory method pattern is not the same as the factory pattern, which we will NOT be covering in this presentation. <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 18. Object Oriented Design Patterns for PHP The Factory Method Pattern <?php /**  * A factory method implementation  */ abstract class  Creator  {      /**      * Abstract factory method to be defined by child classes      */      abstract public function  createObject ( $type ); } class  ConcreteCreatorA  extends  Creator  {     public function  createObject ( $type ) {         switch ( $type ) {              // Handle cases for concrete classes          }     } } class  ConcreteCreatorB  extends  Creator  {     public function  createObject ( $type ) {         switch ( $type ) {              // Handle cases for concrete classes          }     } } $b  = new  ConcreteCreatorB ; $b -> create ( 'ConcreteProductB' ); <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 19. Object Oriented Design Patterns for PHP The Factory Method Pattern, an alternative <?php /**  * A little class to handle creation of objects  */ class  Lib_Factory  {      /**      * Create an object of type $name      */      public static function  createObject ( $name ,  $args  = array()) {          /**           * Move our class name into a file path, turning names like          * App_Db_Handler into something like App/Db/Handler.php          */          $file  =  str_replace ( '_' ,  PATH_SEPARATOR ,  $name ) .  '.php' ;                   // Get the file          if ( file_exists ( $file )) {             require_once  $file ;              $obj  = new  $name ( $args );             return  $obj ;         }                   // Throw an exception if we get here         throw new  Exception ( &quot;The class name $name could not be instantiated.&quot; );     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 20. Object Oriented Design Patterns for PHP The Factory Method Pattern benefits: Encapsulates object creation Allows a range of functionality for error trapping, loading, etc Does not need to know anything about what it is creating Easy to read, easy to understand Lightweight, fast and can be made into a static method <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> Is there a way to tie all these patterns together into something usable? I think we can, but first...
  • 21. Object Oriented Design Patterns for PHP The Strategy Pattern The strategy pattern defines and encapsulates a set of algorithms and makes them interchangeable, allowing the algorithms to vary independent from the objects that use them. Uh, what? <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 22. Object Oriented Design Patterns for PHP The Strategy Pattern Encapsulates what changes and leaves what doesn't change alone Makes encapsulated algorithms interchangeable Favors composition over inheritance <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> With some patterns, like the Strategy Pattern, the best way to ”get” it is to see it. Let's have a look...
  • 23. Object Oriented Design Patterns for PHP The Strategy Pattern, part 1 <?php abstract class  Computer  {     public  $type ;     public  $platform ;          abstract public function  identify ();          public function  transport () {          $this -> type -> transport ();     }          public function  openTerminal () {          $this -> platform -> terminal ();     }          public function  closeTerminal () {         echo  &quot;Close the terminal: type e-x-i-t, hit <enter>&quot; ;     }          public function  setComputerType ( ComputerType $type ) {          $this -> type  =  $type ;     }          public function  setPlatform ( ComputerPlatform $platform ) {          $this -> platform  =  $platform ;     }          public function  gotoNext () { echo  &quot;Moving on...&quot; ; } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 24. Object Oriented Design Patterns for PHP The Strategy Pattern, part 2 <?php interface  ComputerType  {     public function  transport (); } class  ComputerType_Laptop  implements  ComputerType  {     public function  transport () {         echo  &quot;Transporting... Put the laptop in the bag and no one gets hurt.&quot; ;     } } class  ComputerType_Desktop  implements  ComputerType  {     public function  transport () {         echo  &quot;Transporting... Get the boxes, load it up, move it.&quot; ;     } } class  ComputerType_Server  implements  ComputerType  {     public function  transport () {         echo  &quot;Transporting... Seriously? Yeah, right. Transport this!&quot; ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 25. Object Oriented Design Patterns for PHP The Strategy Pattern, part 3 <?php interface  ComputerPlatform  {     public function  terminal (); } class  ComputerPlatform_Mac  implements  ComputerPlatform  {     public function  terminal () {         echo  &quot;Open the terminal: Go to applications -> terminal.&quot; ;     } } class  ComputerPlatform_Ubuntu  implements  ComputerPlatform  {     public function  terminal () {         echo  &quot;Open the terminal: Go to applications -> accessories -> terminal.&quot; ;     } } class  ComputerPlatform_Windows  implements  ComputerPlatform  {     public function  terminal () {         echo  &quot;Open the terminal: I am not smart enough to have a terminal but ...&quot; ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 26. Object Oriented Design Patterns for PHP The Strategy Pattern, part 4 <?php class  Computer_Mac  extends  Computer  {     public function  __construct () {          $this -> type  = new  ComputerType_Laptop ;          $this -> platform  = new  ComputerPlatform_Mac ;     }          public function  identify () {         echo  &quot;I am a mac.&quot; ;     } } class  Computer_PC  extends  Computer  {     public function  __construct () {          $this -> type  = new  ComputerType_Desktop ;          $this -> platform  = new  ComputerPlatform_Windows ;     }          public function  identify () {         echo  &quot;I'm a PC (or is that POS?).&quot; ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 27. Object Oriented Design Patterns for PHP The Strategy Pattern, part 4 continued <?php class  Computer_Server  extends  Computer  {     public function  __construct () {          $this -> type  = new  ComputerType_Server ;          $this -> platform  = new  ComputerPlatform_Ubuntu ;     }          public function  identify () {         echo  &quot;I am Ubuntu, one of a multitude of flavors of linux.&quot; ;     } } <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 28. Object Oriented Design Patterns for PHP The Strategy Pattern, part 5 <?php class  Computer_Identifier  {     public function  __construct () {          $mac  = new  Computer_Mac ;          $mac -> identify ();          $mac -> openTerminal ();          $mac -> closeTerminal ();          $mac -> gotoNext ();          $pc  = new  Computer_PC ;          $pc -> identify ();          $pc -> openTerminal ();          $pc -> closeTerminal ();          $pc -> gotoNext ();          $linux  = new  Computer_Server ;          $linux -> identify ();          $linux -> transport ();     } } $comps  = new  Computer_Identifier ; <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 29. Object Oriented Design Patterns for PHP The Strategy Pattern, in action I am a mac. Open the terminal: Go to applications -> terminal. Close the terminal: type e-x-i-t, hit <enter> Moving on... I'm a PC (or is that POS?). Open the terminal: I am not smart enough to have a terminal but you can go to start -> all programs -> accessories -> command prompt. Close the terminal: type e-x-i-t, hit <enter> Moving on... I am Ubuntu, one of a multitude of flavors of linux. Transporting... Seriously? Yeah, right. Transport this! <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 30. Object Oriented Design Patterns for PHP Notes about the Strategy Pattern Probably one of the most common patterns in OOP One of the most powerful patterns in development Opens a wealth of possibility when understood Very flexible when favoring composition over inheritance Encapsulates what changes to allow for greater extendability <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?>
  • 31. Object Oriented Design Patterns for PHP <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> Knowing what we know now, can you think of how these patterns can be applied to your applications to make for faster, more robust and cleaner application code? Maybe we can look at some code...
  • 32. Object Oriented Design Patterns for PHP <?php if ( $this ->try && ! $this ->succeed()) $this ->try++; /* Robert Gonzalez, 2008-12-18 */ ?> Design patterns are a great way to modularize your code and create reusable structures. But they mean nothing if they go unused. Go code something. Much more information about design patterns, reusable code and object oriented programming can be found by simply typing those keywords into the Google search box :) http://www.robert-gonzalez.com [email_address]