SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Design Patterns
in PHP
Jason Straughan - Grok Interactive, LLC
What are design patterns?
Wikipedia says
...a general reusable solution to a commonly
occurring problem within a given context in
software design...a description or template for
how to solve a problem that can be used in
many different situations. Patterns are
formalized best practices that the programmer
must implement themselves in the application.
What are design patterns?
Design patterns are concepts and best
practices for solving common software
development problems.
When to use
You already are using them.
To solve common problems.
To express architecture or solutions.
Recognize in existing code.
How to use
Not plug-and-play.
Implement as needed.
Use in frameworks and libraries.
Impress your friends.
Common Patterns in PHP
● Factory
● Singleton
● Delegate
● Decorator
● Strategy
● Observer
● Adapter
● State
● Iterator
● Front Controller
● MVC
● Active Record
The Factory Pattern
Creates objects without having to instantiate
the classes directly.
Factories create objects.
When to use the
Factory Pattern
Keep DRY when complex object creation
needs to be reusable.
Encapsulate several objects or steps into new
object creation.
class Factory {
public function create_thing() {
return new Thing();
}
}
class Thing {
public function do_something() {
echo 'Hello PHPeople';
}
}
Example of a
Factory Pattern
$factory = new Factory();
$thing = $factory->create_thing();
$thing->do_something();
// 'Hello PHPeople'
Example of a
Factory Pattern
class SMSFactory {
public function create_messenger() {
// setup SMS API
return new SMSMessage();
}
}
class SMSMessage {
public function __construct() {
// Setup SMS API
}
public function send_message($message) {
// Send $message via SMS
}
}
$factory = new SMSFactory();
$messenger = $factory->create_messenger();
$messenger->send_message('Hello PHPeople');
The Singleton Pattern
Creates object without direct instantiation and
does not allow more that one instance of self.
Singletons ensure only one instance of an
object at any given time.
When to use the
Singleton Pattern
Require only one instance of an class.
Need only one connection to a server.
Example of a
Singleton Pattern
$var = SomeSingleton::getInstance();
// Returns instance of SomeSingleton
$var = new SomeSingleton();
// Fatal error:
// Call to private SomeSingleton::__construct()
class SomeSingleton {
public static $instance;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!(self::$instance instanceof self)) {
self::$instance = new self();
}
return self::$instance;
}
}
Example of a
Singleton Pattern
public static function getInstance() {
if (!(self::$instance instanceof self)) {
self::$instance = new self();
}
return self::$instance;
}
...
}
$db = Database::getInstance();
$db->query(...);
class Database {
private $db;
public static $instance;
private function __construct() {
// code to connect to db
}
private function __clone() {}
Use associated objects to perform duties to
complete tasks.
Delegation of tasks to helpers based on needs.
The Delegate Pattern
When to use the
Delegate Pattern
Object uses functionality in other classes.
Remove coupling to reusable code or abstract
logic and tasks.
Example of a
Delegate Pattern
$delegated = new SomeDelegate();
echo $delegated->do_something();
// 'Hello PHPeople'
class SomeDelegate {
public function do_something() {
$delegate = new Delegate();
return $delegate->output();
}
}
class Delegate {
public function output() {
return 'Hello PHPeople';
}
}
class Notifier {
...
public function send_notification() {
...
$this->setup_mail_client();
$this->send_email();
...
}
protected function setup_mail_client() {
...
}
protected function send_email() {
...
}
}
Example of a
Delegate Pattern
class Notifier {
...
public function send_notification() {
$mailer = new Mailer();
$mailer->send_email();
...
}
}
class Mailer {
private function __construct() {
$this->setup_mail_client();
}
...
public function send_email() {
...
}
}
Delegated
The Decorator Pattern
Decorators add functionality to an object
without changing the object’s behavior.
When to use the
Decorator Pattern
Need to add features or methods to an object
that are not part of the core logic.
Need extended functionality for specific use
cases.
Example of a
Decorator Pattern
class SomeObject {
public $subject;
}
class SomeObjectDecorator {
private $object;
public function __construct(SomeObject $object) {
$this->object = $object;
}
public function say_hello() {
return "Hello {$this->object->subject}";
}
}
$obj = new SomeObject();
$obj->subject = 'PHPeople';
$decorated = new SomeObjectDecorator($obj);
echo $decorated->say_hello();
// 'Hello PHPeople'
class User {
public $first_name = '';
public $last_name = '';
}
class UserDecorator {
private $user;
public function __construct(User $user) {
$this->user = $user;
}
public function full_name() {
return "{$this->user->first_name} {$this->user->last_name}";
}
}
Example of a
Decorator Pattern
$user = new User();
$user->first_name = 'Chuck';
$user->last_name = 'Norris';
$decorated_user = new UserDecorator($user);
echo $decorated_user->full_name();
// 'Chuck Norris'
The Strategy Pattern
“The strategy pattern defines a family of
algorithms, encapsulates each one, and makes
them interchangeable” - Wikipedia
Strategy Pattern allows you to pick from a
group of algorithms as needed.
When to use the
Strategy Pattern
Criteria based data manipulation.
● Search result ranking
● Weighted Voting
● A/B Testing
● Environment based decisions
● Platform specific code
Example of a
Strategy Pattern
switch ($message_type) {
case 'email':
// Send Email
// Lots of code
break;
case 'twitter':
// Send Tweet
// More code here
break;
}
abstract class MessageStrategy {
public function __construct() {}
public function send_message($message) {}
}
class EmailMessageStrategy extends MessageStrategy {
function send_message($message) {
// send email message
}
}
class TwitterMessageStrategy extends MessageStrategy {
function send_message($message) {
// send tweet
}
}
Example of a
Strategy Pattern
class Message {
public $messaging_method;
function __construct(MessageStrategy $messaging_strategy) {
$this->messaging_method = $messaging_strategy;
}
}
$message = new Message(new EmailMessageStrategy());
$message->messaging_method->send_message('Hello PHPeople');
Objects (subjects) register other objects
(observers) that react to state changes of their
subject.
Observers look for changes and do something.
The Observer Pattern
When to use the
Observer Pattern
State changes of an object affect other objects
or datasets.
● Event handling
● Data persistence
● Logging
Observer Pattern in
PHP using the SPL
SplSubject {
/* Methods */
abstract public void attach ( SplObserver $observer )
abstract public void detach ( SplObserver $observer )
abstract public void notify ( void )
}
SplObserver {
/* Methods */
abstract public void update ( SplSubject $subject )
}
class Subject implements SplSubject {
public $observers = array();
public $output = null;
public function attach (SplObserver $observer ) {
$this->observers[] = $observer;
}
public function detach (SplObserver $observer ) {
$this->observers = array_diff($this->observers, array($observer));
}
public function notify ( ) {
foreach($this->observers as $observer) {
$observer->update($this);
}
}
}
Example of a
Observer Pattern (w/ SPL)
class Observer implements SplObserver {
public function update (SplSubject $subject ) {
echo $subject->output;
}
}
$subject = new Subject;
$subject->attach(new Observer);
$subject->notify();
// Null
$subject->output = "Hello PHPeople";
$subject->notify();
// 'Hello PHPeople'
Review
Design Pattern are:
● Reusable concepts
● Best practice solutions
● Tried and true methods
Continuing Education
Design Patterns: Elements of Reusable Object-
Oriented Software
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides
Code and Slides provided online
https://github.com/GrokInteractive/php_design_patterns_talk
?>

Weitere ähnliche Inhalte

Was ist angesagt?

The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern PresentationJAINIK PATEL
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignYoung-Ho Cho
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Garbage collection in .net (basic level)
Garbage collection in .net (basic level)Garbage collection in .net (basic level)
Garbage collection in .net (basic level)Larry Nung
 
Android resources
Android resourcesAndroid resources
Android resourcesma-polimi
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternMudasir Qazi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Classes and Objects
Classes and Objects  Classes and Objects
Classes and Objects yndaravind
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 

Was ist angesagt? (20)

The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Garbage collection in .net (basic level)
Garbage collection in .net (basic level)Garbage collection in .net (basic level)
Garbage collection in .net (basic level)
 
Android resources
Android resourcesAndroid resources
Android resources
 
Design pattern
Design patternDesign pattern
Design pattern
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Classes and Objects
Classes and Objects  Classes and Objects
Classes and Objects
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Spring Core
Spring CoreSpring Core
Spring Core
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 

Andere mochten auch

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 2012Aaron Saray
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in phpDavid Stockton
 
Design patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMDesign patterns in PHP - PHP TEAM
Design patterns in PHP - PHP TEAMNishant 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.3Fabien Potencier
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPRobertGonzalez
 
Enterprise PHP: mappers, models and services
Enterprise PHP: mappers, models and servicesEnterprise PHP: mappers, models and services
Enterprise PHP: mappers, models and servicesAaron Saray
 
A la recherche du code mort
A la recherche du code mortA la recherche du code mort
A la recherche du code mortDamien Seguy
 
硬件体系架构浅析
硬件体系架构浅析硬件体系架构浅析
硬件体系架构浅析frogd
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Google Analytics Implementation Checklist
Google Analytics Implementation ChecklistGoogle Analytics Implementation Checklist
Google Analytics Implementation ChecklistPadiCode
 
Hunt for dead code
Hunt for dead codeHunt for dead code
Hunt for dead codeDamien Seguy
 
Php 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php beneluxPhp 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php beneluxDamien Seguy
 
php & performance
 php & performance php & performance
php & performancesimon8410
 
Php in the graph (Gremlin 3)
Php in the graph (Gremlin 3)Php in the graph (Gremlin 3)
Php in the graph (Gremlin 3)Damien Seguy
 
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphpReview unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphpDamien Seguy
 
Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析frogd
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonightDamien Seguy
 
Google Analytics Campaign Tracking Fundamentals
Google Analytics Campaign Tracking FundamentalsGoogle Analytics Campaign Tracking Fundamentals
Google Analytics Campaign Tracking FundamentalsKayden Kelly
 

Andere mochten auch (20)

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
 
Common design patterns in php
Common design patterns in phpCommon design patterns in php
Common design patterns in php
 
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
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
Enterprise PHP: mappers, models and services
Enterprise PHP: mappers, models and servicesEnterprise PHP: mappers, models and services
Enterprise PHP: mappers, models and services
 
Php performance-talk
Php performance-talkPhp performance-talk
Php performance-talk
 
A la recherche du code mort
A la recherche du code mortA la recherche du code mort
A la recherche du code mort
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
硬件体系架构浅析
硬件体系架构浅析硬件体系架构浅析
硬件体系架构浅析
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Google Analytics Implementation Checklist
Google Analytics Implementation ChecklistGoogle Analytics Implementation Checklist
Google Analytics Implementation Checklist
 
Hunt for dead code
Hunt for dead codeHunt for dead code
Hunt for dead code
 
Php 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php beneluxPhp 7.2 compliance workshop php benelux
Php 7.2 compliance workshop php benelux
 
php & performance
 php & performance php & performance
php & performance
 
Php in the graph (Gremlin 3)
Php in the graph (Gremlin 3)Php in the graph (Gremlin 3)
Php in the graph (Gremlin 3)
 
Review unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphpReview unknown code with static analysis - bredaphp
Review unknown code with static analysis - bredaphp
 
Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析Oracle rac资源管理算法与cache fusion实现浅析
Oracle rac资源管理算法与cache fusion实现浅析
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
 
Google Analytics Campaign Tracking Fundamentals
Google Analytics Campaign Tracking FundamentalsGoogle Analytics Campaign Tracking Fundamentals
Google Analytics Campaign Tracking Fundamentals
 

Ähnlich wie Design patterns in PHP

10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboardsDenis Ristic
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8Alexei Gorobets
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Savio Sebastian
 
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
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 

Ähnlich wie Design patterns in PHP (20)

10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
 
Design Patterns and Usage
Design Patterns and UsageDesign Patterns and Usage
Design Patterns and Usage
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2
 
OOP
OOPOOP
OOP
 
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...
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Design attern in php
Design attern in phpDesign attern in php
Design attern in php
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Only oop
Only oopOnly oop
Only oop
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 

Mehr von Jason Straughan

Navigating Imposter Syndrome
Navigating Imposter SyndromeNavigating Imposter Syndrome
Navigating Imposter SyndromeJason Straughan
 
Innovative Ways to Teach High-Tech Skills
Innovative Ways to Teach High-Tech SkillsInnovative Ways to Teach High-Tech Skills
Innovative Ways to Teach High-Tech SkillsJason Straughan
 
The 5 things you need to know to start a software project
The 5 things you need to know to start a software projectThe 5 things you need to know to start a software project
The 5 things you need to know to start a software projectJason Straughan
 
The future of cloud programming
The future of cloud programmingThe future of cloud programming
The future of cloud programmingJason Straughan
 
Happy Developers are Better Developers
Happy Developers are Better DevelopersHappy Developers are Better Developers
Happy Developers are Better DevelopersJason Straughan
 

Mehr von Jason Straughan (7)

Navigating Imposter Syndrome
Navigating Imposter SyndromeNavigating Imposter Syndrome
Navigating Imposter Syndrome
 
MVP Like a BOSS
MVP Like a BOSSMVP Like a BOSS
MVP Like a BOSS
 
Innovative Ways to Teach High-Tech Skills
Innovative Ways to Teach High-Tech SkillsInnovative Ways to Teach High-Tech Skills
Innovative Ways to Teach High-Tech Skills
 
Optimizing the SDLC
Optimizing the SDLCOptimizing the SDLC
Optimizing the SDLC
 
The 5 things you need to know to start a software project
The 5 things you need to know to start a software projectThe 5 things you need to know to start a software project
The 5 things you need to know to start a software project
 
The future of cloud programming
The future of cloud programmingThe future of cloud programming
The future of cloud programming
 
Happy Developers are Better Developers
Happy Developers are Better DevelopersHappy Developers are Better Developers
Happy Developers are Better Developers
 

Kürzlich hochgeladen

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 

Kürzlich hochgeladen (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Design patterns in PHP

  • 1. Design Patterns in PHP Jason Straughan - Grok Interactive, LLC
  • 2. What are design patterns? Wikipedia says ...a general reusable solution to a commonly occurring problem within a given context in software design...a description or template for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that the programmer must implement themselves in the application.
  • 3. What are design patterns? Design patterns are concepts and best practices for solving common software development problems.
  • 4. When to use You already are using them. To solve common problems. To express architecture or solutions. Recognize in existing code.
  • 5. How to use Not plug-and-play. Implement as needed. Use in frameworks and libraries. Impress your friends.
  • 6. Common Patterns in PHP ● Factory ● Singleton ● Delegate ● Decorator ● Strategy ● Observer ● Adapter ● State ● Iterator ● Front Controller ● MVC ● Active Record
  • 7. The Factory Pattern Creates objects without having to instantiate the classes directly. Factories create objects.
  • 8. When to use the Factory Pattern Keep DRY when complex object creation needs to be reusable. Encapsulate several objects or steps into new object creation.
  • 9. class Factory { public function create_thing() { return new Thing(); } } class Thing { public function do_something() { echo 'Hello PHPeople'; } } Example of a Factory Pattern $factory = new Factory(); $thing = $factory->create_thing(); $thing->do_something(); // 'Hello PHPeople'
  • 10. Example of a Factory Pattern class SMSFactory { public function create_messenger() { // setup SMS API return new SMSMessage(); } } class SMSMessage { public function __construct() { // Setup SMS API } public function send_message($message) { // Send $message via SMS } } $factory = new SMSFactory(); $messenger = $factory->create_messenger(); $messenger->send_message('Hello PHPeople');
  • 11. The Singleton Pattern Creates object without direct instantiation and does not allow more that one instance of self. Singletons ensure only one instance of an object at any given time.
  • 12. When to use the Singleton Pattern Require only one instance of an class. Need only one connection to a server.
  • 13. Example of a Singleton Pattern $var = SomeSingleton::getInstance(); // Returns instance of SomeSingleton $var = new SomeSingleton(); // Fatal error: // Call to private SomeSingleton::__construct() class SomeSingleton { public static $instance; private function __construct() {} private function __clone() {} public static function getInstance() { if (!(self::$instance instanceof self)) { self::$instance = new self(); } return self::$instance; } }
  • 14. Example of a Singleton Pattern public static function getInstance() { if (!(self::$instance instanceof self)) { self::$instance = new self(); } return self::$instance; } ... } $db = Database::getInstance(); $db->query(...); class Database { private $db; public static $instance; private function __construct() { // code to connect to db } private function __clone() {}
  • 15. Use associated objects to perform duties to complete tasks. Delegation of tasks to helpers based on needs. The Delegate Pattern
  • 16. When to use the Delegate Pattern Object uses functionality in other classes. Remove coupling to reusable code or abstract logic and tasks.
  • 17. Example of a Delegate Pattern $delegated = new SomeDelegate(); echo $delegated->do_something(); // 'Hello PHPeople' class SomeDelegate { public function do_something() { $delegate = new Delegate(); return $delegate->output(); } } class Delegate { public function output() { return 'Hello PHPeople'; } }
  • 18. class Notifier { ... public function send_notification() { ... $this->setup_mail_client(); $this->send_email(); ... } protected function setup_mail_client() { ... } protected function send_email() { ... } } Example of a Delegate Pattern class Notifier { ... public function send_notification() { $mailer = new Mailer(); $mailer->send_email(); ... } } class Mailer { private function __construct() { $this->setup_mail_client(); } ... public function send_email() { ... } } Delegated
  • 19. The Decorator Pattern Decorators add functionality to an object without changing the object’s behavior.
  • 20. When to use the Decorator Pattern Need to add features or methods to an object that are not part of the core logic. Need extended functionality for specific use cases.
  • 21. Example of a Decorator Pattern class SomeObject { public $subject; } class SomeObjectDecorator { private $object; public function __construct(SomeObject $object) { $this->object = $object; } public function say_hello() { return "Hello {$this->object->subject}"; } } $obj = new SomeObject(); $obj->subject = 'PHPeople'; $decorated = new SomeObjectDecorator($obj); echo $decorated->say_hello(); // 'Hello PHPeople'
  • 22. class User { public $first_name = ''; public $last_name = ''; } class UserDecorator { private $user; public function __construct(User $user) { $this->user = $user; } public function full_name() { return "{$this->user->first_name} {$this->user->last_name}"; } } Example of a Decorator Pattern $user = new User(); $user->first_name = 'Chuck'; $user->last_name = 'Norris'; $decorated_user = new UserDecorator($user); echo $decorated_user->full_name(); // 'Chuck Norris'
  • 23. The Strategy Pattern “The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable” - Wikipedia Strategy Pattern allows you to pick from a group of algorithms as needed.
  • 24. When to use the Strategy Pattern Criteria based data manipulation. ● Search result ranking ● Weighted Voting ● A/B Testing ● Environment based decisions ● Platform specific code
  • 25. Example of a Strategy Pattern switch ($message_type) { case 'email': // Send Email // Lots of code break; case 'twitter': // Send Tweet // More code here break; }
  • 26. abstract class MessageStrategy { public function __construct() {} public function send_message($message) {} } class EmailMessageStrategy extends MessageStrategy { function send_message($message) { // send email message } } class TwitterMessageStrategy extends MessageStrategy { function send_message($message) { // send tweet } } Example of a Strategy Pattern class Message { public $messaging_method; function __construct(MessageStrategy $messaging_strategy) { $this->messaging_method = $messaging_strategy; } } $message = new Message(new EmailMessageStrategy()); $message->messaging_method->send_message('Hello PHPeople');
  • 27. Objects (subjects) register other objects (observers) that react to state changes of their subject. Observers look for changes and do something. The Observer Pattern
  • 28. When to use the Observer Pattern State changes of an object affect other objects or datasets. ● Event handling ● Data persistence ● Logging
  • 29. Observer Pattern in PHP using the SPL SplSubject { /* Methods */ abstract public void attach ( SplObserver $observer ) abstract public void detach ( SplObserver $observer ) abstract public void notify ( void ) } SplObserver { /* Methods */ abstract public void update ( SplSubject $subject ) }
  • 30. class Subject implements SplSubject { public $observers = array(); public $output = null; public function attach (SplObserver $observer ) { $this->observers[] = $observer; } public function detach (SplObserver $observer ) { $this->observers = array_diff($this->observers, array($observer)); } public function notify ( ) { foreach($this->observers as $observer) { $observer->update($this); } } } Example of a Observer Pattern (w/ SPL) class Observer implements SplObserver { public function update (SplSubject $subject ) { echo $subject->output; } } $subject = new Subject; $subject->attach(new Observer); $subject->notify(); // Null $subject->output = "Hello PHPeople"; $subject->notify(); // 'Hello PHPeople'
  • 31. Review Design Pattern are: ● Reusable concepts ● Best practice solutions ● Tried and true methods
  • 32. Continuing Education Design Patterns: Elements of Reusable Object- Oriented Software Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides Code and Slides provided online https://github.com/GrokInteractive/php_design_patterns_talk
  • 33. ?>