SlideShare a Scribd company logo
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
?>

More Related Content

What's hot (20)

PPTX
Modules in AngularJs
K Arunkumar
 
PDF
Client-side JavaScript
Lilia Sfaxi
 
PDF
Why Vue.js?
Jonathan Goode
 
PDF
HTML & CSS Masterclass
Bernardo Raposo
 
PPTX
Repository design pattern in laravel
Sameer Poudel
 
PPTX
Html 5 tutorial - By Bally Chohan
ballychohanuk
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PPTX
Design Pattern - MVC, MVP and MVVM
Mudasir Qazi
 
PPTX
Object Oriented Programming In JavaScript
Forziatech
 
PDF
Angular components
Sultan Ahmed
 
PDF
How To be a Backend developer
Ramy Hakam
 
PPTX
Angular 2.0 forms
Eyal Vardi
 
PPTX
Factory Method Pattern
Anjan Kumar Bollam
 
PPTX
JSON: The Basics
Jeff Fox
 
PDF
Javascript Arrow function
tanerochris
 
PPTX
React js
Oswald Campesato
 
PPTX
Adapter Design Pattern
Adeel Riaz
 
PDF
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
PDF
Introduction to HTML5
Gil Fink
 
Modules in AngularJs
K Arunkumar
 
Client-side JavaScript
Lilia Sfaxi
 
Why Vue.js?
Jonathan Goode
 
HTML & CSS Masterclass
Bernardo Raposo
 
Repository design pattern in laravel
Sameer Poudel
 
Html 5 tutorial - By Bally Chohan
ballychohanuk
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Design Pattern - MVC, MVP and MVVM
Mudasir Qazi
 
Object Oriented Programming In JavaScript
Forziatech
 
Angular components
Sultan Ahmed
 
How To be a Backend developer
Ramy Hakam
 
Angular 2.0 forms
Eyal Vardi
 
Factory Method Pattern
Anjan Kumar Bollam
 
JSON: The Basics
Jeff Fox
 
Javascript Arrow function
tanerochris
 
Adapter Design Pattern
Adeel Riaz
 
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
Introduction to HTML5
Gil Fink
 

Viewers also liked (20)

PDF
Your first 5 PHP design patterns - ThatConference 2012
Aaron Saray
 
PDF
Common design patterns in php
David Stockton
 
PDF
Design patterns in PHP - PHP TEAM
Nishant Shrivastava
 
PDF
Design patterns revisited with PHP 5.3
Fabien Potencier
 
ODP
Object Oriented Design Patterns for PHP
RobertGonzalez
 
PDF
Enterprise PHP: mappers, models and services
Aaron Saray
 
PDF
Php performance-talk
Sherif Ramadan
 
PDF
A la recherche du code mort
Damien Seguy
 
PDF
What's new with PHP7
SWIFTotter Solutions
 
PPTX
硬件体系架构浅析
frogd
 
PPTX
Design pattern (Abstract Factory & Singleton)
paramisoft
 
PPT
Google Analytics Implementation Checklist
PadiCode
 
PDF
Hunt for dead code
Damien Seguy
 
PDF
Php 7.2 compliance workshop php benelux
Damien Seguy
 
PDF
php & performance
simon8410
 
PDF
Php in the graph (Gremlin 3)
Damien Seguy
 
PDF
Review unknown code with static analysis - bredaphp
Damien Seguy
 
PDF
Oracle rac资源管理算法与cache fusion实现浅析
frogd
 
PDF
Static analysis saved my code tonight
Damien Seguy
 
PDF
Google Analytics Campaign Tracking Fundamentals
Kayden Kelly
 
Your first 5 PHP design patterns - ThatConference 2012
Aaron Saray
 
Common design patterns in php
David Stockton
 
Design patterns in PHP - PHP TEAM
Nishant Shrivastava
 
Design patterns revisited with PHP 5.3
Fabien Potencier
 
Object Oriented Design Patterns for PHP
RobertGonzalez
 
Enterprise PHP: mappers, models and services
Aaron Saray
 
Php performance-talk
Sherif Ramadan
 
A la recherche du code mort
Damien Seguy
 
What's new with PHP7
SWIFTotter Solutions
 
硬件体系架构浅析
frogd
 
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Google Analytics Implementation Checklist
PadiCode
 
Hunt for dead code
Damien Seguy
 
Php 7.2 compliance workshop php benelux
Damien Seguy
 
php & performance
simon8410
 
Php in the graph (Gremlin 3)
Damien Seguy
 
Review unknown code with static analysis - bredaphp
Damien Seguy
 
Oracle rac资源管理算法与cache fusion实现浅析
frogd
 
Static analysis saved my code tonight
Damien Seguy
 
Google Analytics Campaign Tracking Fundamentals
Kayden Kelly
 
Ad

Similar to Design patterns in PHP (20)

PPT
Design Patterns and Usage
Mindfire Solutions
 
PDF
Design Patterns
Lorna Mitchell
 
PPTX
Design patterns - The Good, the Bad, and the Anti-Pattern
Barry O Sullivan
 
PDF
Design attern in php
Filippo De Santis
 
PDF
Beyond design patterns phpnw14
Anthony Ferrara
 
PPT
5 Design Patterns Explained
Prabhjit Singh
 
PDF
Learning Php Design Patterns William Sanders
arzunakuuse94
 
PDF
Design patterns
Jason Austin
 
PDF
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
PDF
Design patterns illustrated-2015-03
Herman Peeren
 
PPTX
Design pattern-presentation
Rana Muhammad Asif
 
PDF
Design Patterns in PHP
Biju T
 
PPTX
ap assignmnet presentation.pptx
AwanAdhikari
 
PPT
OOP
thinkphp
 
PPTX
Design patterns
Elyes Mejri
 
PDF
designpatterns-.pdf
ElviraSolnyshkina
 
PDF
OOP in PHP
Tarek Mahmud Apu
 
PPT
Design Pattern Zoology
Josh Adell
 
DOCX
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
PDF
software engineering Design Patterns.pdf
mulugetaberihun3
 
Design Patterns and Usage
Mindfire Solutions
 
Design Patterns
Lorna Mitchell
 
Design patterns - The Good, the Bad, and the Anti-Pattern
Barry O Sullivan
 
Design attern in php
Filippo De Santis
 
Beyond design patterns phpnw14
Anthony Ferrara
 
5 Design Patterns Explained
Prabhjit Singh
 
Learning Php Design Patterns William Sanders
arzunakuuse94
 
Design patterns
Jason Austin
 
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
Design patterns illustrated-2015-03
Herman Peeren
 
Design pattern-presentation
Rana Muhammad Asif
 
Design Patterns in PHP
Biju T
 
ap assignmnet presentation.pptx
AwanAdhikari
 
Design patterns
Elyes Mejri
 
designpatterns-.pdf
ElviraSolnyshkina
 
OOP in PHP
Tarek Mahmud Apu
 
Design Pattern Zoology
Josh Adell
 
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
software engineering Design Patterns.pdf
mulugetaberihun3
 
Ad

More from Jason Straughan (7)

PDF
Navigating Imposter Syndrome
Jason Straughan
 
PPTX
MVP Like a BOSS
Jason Straughan
 
PPTX
Innovative Ways to Teach High-Tech Skills
Jason Straughan
 
PDF
Optimizing the SDLC
Jason Straughan
 
PPTX
The 5 things you need to know to start a software project
Jason Straughan
 
PDF
The future of cloud programming
Jason Straughan
 
PDF
Happy Developers are Better Developers
Jason Straughan
 
Navigating Imposter Syndrome
Jason Straughan
 
MVP Like a BOSS
Jason Straughan
 
Innovative Ways to Teach High-Tech Skills
Jason Straughan
 
Optimizing the SDLC
Jason Straughan
 
The 5 things you need to know to start a software project
Jason Straughan
 
The future of cloud programming
Jason Straughan
 
Happy Developers are Better Developers
Jason Straughan
 

Recently uploaded (20)

PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Digital Circuits, important subject in CS
contactparinay1
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 

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. ?>