SlideShare a Scribd company logo
Design Patterns 
Usage and Application 
By Manas Ranjan Sahoo
What is it? 
1. 23 common problems best accepted solutions 
1. Started at IBM 1994 
1. Solutions can be successfully applied to right problems 
1. Using DP the risk of solutions becomes zero 
1. These are well thought and tested solutions 
1. Solution templates for re-occurring programming challenges
1. A design pattern is a solution to common problems that have already been 
discovered, documented, and is in wide use 
1. Don't think of patterns as data structures, or algorithms 
1. Think as if your code as people sending messages, like sending letters, to 
each other 
1. Each object is a 'person'. 
1. The way that you'd organize the 'people' and the patterns they use to send 
messages to each other are the patterns 
1. Patterns deals with relationships and interactions of classes and objects
● A good working knowledge of the patterns saves inventing your own 
solutions to well-known problems. 
● It is analogous to abstract data types: every coder should know what a 
stack, list and queue are and recognize when it is appropriate to use them 
- they should not write code first and then say "Oh I could have just used a 
Stack there." 
● You can alter a given class without changing the rest of the code that 
interacts with it. 
Why
● The key is to learn to identify the scenarios and problems which the 
patterns are meant to address. Then applying the pattern is simply a 
matter of using the right tool for the job. 
● Patterns save time because we don’t have to solve a problem that’s 
already been solved. 
● Design patterns have two major benefits. 
- They provide help us identifying a proven solution which facilitates 
the development of highly cohesive modules with minimal coupling. 
- They make communication between designers more efficient.
Types 
● Factory 
● Singleton 
● Delegate 
● Decorator 
● Strategy 
● Observer 
● Adapter 
● State 
● Iterator 
● Front Controller 
● MVC 
● Active Record
Factory Pattern 
● Most Commonly used 
● A class simply creates the object you want to use 
● We can define a factory as a simple design pattern that give us a 
convenient way to instantiate objects. 
● we create object without exposing the creation logic to the client and refer 
to newly created object using a common interface.
class Thing { 
public function do_something() { 
echo 'Hello PHPeople'; 
} 
} 
class Factory { 
public function create_thing() { 
return new Thing(); 
} 
} 
$factory = new Factory(); 
$thing = $factory->create_thing(); 
$thing->do_something();
Singleton Pattern 
● When designing web applications, we often need to allow access to one 
and only one instance of a particular class. 
● These ensure there is a single class instance and that is global point of 
access for it.
When to Use 
You use a singleton when you need to manage a shared resource. For instance 
a printer spooler. 
Your application should only have a single instance of the spooler in order to 
avoid conflicting request for the same resource. 
Useful when only one object is required across the system.
class DatabaseConnection { 
private static $singleton_instance = null; 
private function construct__() { 
// private ensures 
// that this object is not created as a new intance 
// outside of this class. 
} 
public static function global_instance() { 
static $singleton_instance = null; 
if($singleton_instance === null) { 
$singleton_instance = new DatabaseConnection(); 
} 
return($singleton_instance); 
} 
public function exec_query($query) { 
print "Running query: " . $query; 
} 
}
// We create a database instance by running the static function 
// which returns the singleton instance of the class 
$db_connection = DatabaseConnection::global_instance();
Delegator Pattern 
In this an object, instead of performing one of its stated 
tasks, delegates that task to an associated helper object 
The helper object is known as a delegate. 
Delegate is given the responsibility to execute a task for the 
delegator.
interface Printer { 
public function printline($subject); 
} 
class DelegatePrinter implements Printer { 
public function printline($subject) { 
print $subject; 
} 
} 
class Client { 
public function __construct() { 
$this->printer = new DelegatePrinter; 
} 
public function printData() { 
$this->printer->printline('Some string data'); 
} 
} 
$client = new Client; 
$client->printData();
Decorator Pattern 
Its a pattern that allows behavior to be added to an individual object, either 
statically or dynamically, without affecting the behavior of other objects from 
the same class 
Decorator uses Delegation, it is a subset of delegation. 
Decorator works best when you want to take something that's working and have 
it do something else, but not change the interface at all 
Decorator is used to construct a complex object by using mechanism called 
Delegation
class Book { 
private $title; 
public function __construct($title_in) { 
$this->title = $title_in; 
} 
public function getTitle() { 
return $this->title; 
} 
//we need to implement showtitle method here 
} 
class BookTitleDecorator { 
private $book; 
private $title; 
public function __construct(Book $bookobj) { 
$this->book = $bookobj; 
$this->title = $this->book->getTitle(); 
} 
public function showTitle() { 
return $this->title; 
} 
}
include_once('Book.php'); 
include_once('BookTitleDecorator.php'); 
$DesignPatternBook = new Book("Design Patterns Book explaining 
Decorators"); 
$decorator = new BookTitleDecorator($DesignPatternBook); 
echo $decorator->showTitle();
Strategy Pattern 
Here a context will choose the appropriate concrete extension of a class 
interface. 
Capture the abstraction in an interface, bury implementation details in derived 
classes. 
Strategy lets you change the guts of an object. Decorator lets you change the 
skin. 
Example - Mode of travel to reach Airport
class StrategyContext { ///context for chosing extension 
private $strategy = NULL; 
public function __construct($strategy_id) { 
switch ($strategy_id) { 
case "A": 
$this->strategy = new StrategyA(); 
break; 
} 
} 
public function showBookTitle($book) { 
return $this->strategy->showTitle($book); 
} 
}
interface StrategyInterface { //abstraction captured 
public function showTitle($bookobj); 
} 
class StrategyA implements StrategyInterface { //implementaion detail here 
public function showTitle($bookobj) { 
$title = $bookobj->getTitle(); 
return strtoupper ($title); 
} 
} 
class Book { 
private $title; 
function __construct($title) { $this->title = $title; } 
function getTitle() {return $this->title;} 
}
$book = new Book('PHP for Cats'); 
$strategyContextA = new StrategyContext('A'); 
echo $strategyContextA->showBookTitle($book);
Observer Pattern 
This is a design pattern in which an object, register multiple dependents, called 
observers, and notifies them automatically of any state changes 
Observers look for changes and do something 
Example - A newspaper and subscribers 
Its used when a state change in subject affects other objects, and you don't 
know how many objects need to be changed
abstract class Publisher { 
abstract function attach(Observer $observer); 
abstract function detach(Observer $observer); 
abstract function notify(); 
} 
abstract class Observer { 
abstract function update(Publisher $subject_in); 
} 
class Account extends Publisher 
{ 
public $status = NULL; 
public $_observers = array(); 
function attach(Observer $observer_in) { 
array_push($this->_observers, $observer_in); 
} 
function detach(Observer $observer_in) { 
$this->_observers = array_diff($this->_observers, array($observer_in)); 
} 
public function notify() { 
foreach($this->_observers as $obs) { $obs->update($this); } 
} 
}
class Logger extends Observer 
{ 
public function __construct() { 
} 
public function update(Publisher $pub) 
{ 
//Update status in log table 
echo "Updating status in log table.n"; 
} 
} 
include_once('Account.php'); 
include_once('Logger.php'); 
$account = new Account(); 
$logger = new Logger(); 
$account->attach($logger); 
$account->status = "Expired"; 
$account->notify();
Adapter Pattern 
This pattern is used when we want to convert the interface one class to an 
interface which can be used by another class. 
whenever there is a problem that requires the continued stability of the main 
platform and does not disrupt the existing application flow, the Adapter 
Design Pattern could be used in developing the solution. 
Real-world examples might be a language translator, or a mobile charger. 
It involves a single class called adapter which is responsible for communication 
between 2 incompatible classes.
class Book { 
private $title; 
private $price; 
function __construct($title, $price) { 
$this->title = $title; 
$this->price = $price; 
} 
function getTitle() { 
return $this->title; 
} 
function getPrice() { 
return $this->price; 
} 
}
class BookAdapter { 
private $book; 
function __construct(Book $bookobj) { 
$this->book = $bookobj; 
} function getTitleAndPrice() { 
return $this->book->getTitle().' - '.$this->book->getPrice(); 
} 
} 
$book = new Book("Design Patterns", "$125"); 
$bookAdapter = new BookAdapter($book); 
print('Title and Price: '.$bookAdapter->getTitleAndPrice());
State Pattern 
All our final decisions are made in a state of mind that is not going to last — 
Marcel Proust 
The purpose is to allow an object to change its behavior when the state 
changes. 
It is used to allow an object to changes it’s behaviour when it’s internal state 
changes 
A class will change it's behavior when circumstances change.
interface State { 
function press(StopWatchContext $context); 
} 
class StopState implements State { 
public function press(StopWatchContext $context) { 
$time = (microtime(TRUE) * 1000) - $context->getStartTime(); 
printf("The stop watch is stopped. [Time] %d MS <br>", $time);; 
$context->setState($context->getStartState()); // State is changed here 
} 
} 
class StartState implements State { 
public function press(StopWatchContext $context) { 
echo "The stop watch is running..<br>"; 
$context->setState($context->getStopState()); // State is changed here 
} 
} 
class ResetState implements State { 
public function press(StopWatchContext $context) { 
echo "The stop watch is reset. <br>"; 
$context->setStartTime(microtime(TRUE) * 1000); 
$context->setState($context->getStartState()); // State is changed here 
} 
}
class StopWatchContext { 
private $state; 
private $startTime; 
private $startState; 
private $stopState; 
private $resetState; 
public function __construct() { 
$this->setStartTime(); 
$this->startState = new StartState(); 
$this->stopState = new StopState(); 
$this->resetState = new ResetState(); 
$this->state = $this->startState; 
} 
public function setState(State $state) { 
$this->state = $state; 
} 
public function pressButton() { 
$this->state->press($this); 
}
public function resetButton() { 
$this->setState(new ResetState()); 
$this->pressButton(); 
} 
public function getStartTime() { 
return $this->startTime; 
} 
public function setStartTime() { 
$this->startTime = microtime(TRUE) * 1000; 
} 
public function getStartState() { 
return $this->startState; 
} 
public function getStopState() { 
return $this->stopState; 
} 
public function getResetState() { 
return $this->resetState; 
} 
}
$timer = new StopWatchContext(); 
$timer->pressButton(); //started 
usleep(1200 * 1000); // sleeping 1.2 seconds 
$timer->pressButton(); //stopped 
$timer->pressButton(); //started 
usleep(2000 * 1000); //sleeping 1.7 seconds (3200 MS) 
$timer->pressButton();//stopped 
$timer->resetButton(); //reset 
$timer->pressButton();//started 
sleep(2);//sleeping 2 seconds 
$timer->pressButton(); //stopped
Iterator Pattern 
Not all objects are the same when it comes to looping. 
It helps construct objects that can provide a single standard interface to loop or 
iterate through any type of countable data. 
When dealing with countable data that needs to be traversed, creating an 
object based on the Iterator Design Pattern is the best solution.
class AddressDisplay 
{ 
private $addressType; 
private $addressText; 
public function setAddressType($addressType) 
{ 
$this->addressType = $addressType; 
} 
public function getAddressType() 
{ 
return $this->addressType; 
} 
public function setAddressText($addressText) 
{ 
$this->addressText = $addressText; 
} 
public function getAddressText() 
{ 
return $this->addressText; 
} 
}
class EmailAddress 
{ 
private $emailAddress; 
public function getEmailAddress() 
{ 
return $this->emailAddress; 
} 
public function setEmailAddress($address) 
{ 
$this->emailAddress = $address; 
} 
} 
class PhysicalAddress 
{ 
private $streetAddress; 
private $city; 
private $state; 
private $postalCode;
public function __construct($streetAddress, $city, $state, $postalCode) 
{ 
$this->streetAddress = $streetAddress; 
$this->city = $city; $this->state = $state; $this->postalCode = $postalCode; 
} 
public function getStreetAddress() { 
return $this->streetAddress; 
} 
public function getCity() { 
return $this->city; 
} 
public function getState() { 
return $this->state; 
} 
public function getPostalCode() { 
return $this->postalCode; 
} 
public function setStreetAddress($streetAddress) { 
$this->streetAddress = $streetAddress; 
} 
public function setCity($city) { 
$this->city = $city; 
}
public function setState($state) 
{ 
$this->state = $state; 
} 
public function setPostalCode($postalCode) 
{ 
$this->postalCode = $postalCode; 
} 
} 
class PersonAddressIterator implements AddressIterator 
{ 
private $emailAddresses; 
private $physicalAddresses; 
private $position; 
public function __construct($emailAddresses) 
{ 
$this->emailAddresses = $emailAddresses; 
$this->position = 0; 
}
public function hasNext() 
{ 
if ($this->position >= count($this->emailAddresses) || 
$this->emailAddresses[$this->position] == null) { 
return false; 
} else { 
return true; 
}} 
public function next() 
{ 
$item = $this->emailAddresses[$this->position]; 
$this->position = $this->position + 1; 
return $item; 
} 
}
Front Controller Pattern 
It relates to the design of web applications. 
It "provides a centralized entry point for handling requests 
All request send to the application are processed with it, which then redirects 
each request to the corresponding Action Controller 
Example: The login.php on specific request instantiate further objects and call 
methods to handle the particular task(s) required. 
Yii, CakePHP, Laravel, Symfony, CodeIgniter and Zend Framework, Magento, 
MVC frameworks uses front controller
MVC Pattern 
Its a for implementing user interfaces. 
It divides a given software application into three interconnected parts, so as to separate 
internal representations of information from users. 
The model directly manages the data, logic and rules of the application. 
A view can be any output representation of information. 
The controller, accepts input and converts it to commands for the model or view.
Active Record Pattern 
This is pattern found in software that stores its data in relational databases. 
The interface of the object using this pattern would include functions such as 
Insert, Update, and Delete operations 
We can say this as an approach to accessing data in a database. 
Laravel contains an ORM called 'Eloquent' which implements the active record 
pattern. 
CakePHP's ORM implements the active record pattern. 
A database table is wrapped into a class. 
An object instance is tied to a single row in the table.
Magento Patterns 
MVC 
Magento leverages xml to drive the configuration and actions of the application on top of 
the regular Model-View-Controller architecture. 
Front Controller 
Magneto has a single entry point (index.php) for all of it's requests. 
Factory 
The Factory Method is used to instantiate classes in Magento. 
Singleton 
In magento Singleton pattern is instantiated for Blocks and Classes.
Registry 
Its basically a pattern that allows any object or data to be available in a public global scope for any 
resource to use. 
Object Pool 
The Object Pool Pattern keeps objects ready for use over and over again instead of re-instantiating 
them and destroying them once finished. 
Iterator 
Magento allows an object traverse through the elements of another class. 
The core/resource_iterator model allows you to get the collection item data one by one executing 
corresponding SQL query. 
Module 
Magneto is based on modular programming and emphasizes the grouping of functionality of a 
program into independent, interchangeable modules.
Observer 
Magento uses observer pattern by providing event listeners through which other components of the 
application can "hook" into this event listener and execute their code.
References 
http://www.wrox.com/WileyCDA/WroxTitle/Professional-PHP-Design- 
Patterns.productCd-0470496703.html 
http://www.phptherightway.com/pages/Design-Patterns.html 
http://www.fluffycat.com/PHP-Design-Patterns/ 
http://en.wikipedia.org/wiki/Design_Patterns 
http://www.oodesign.com 
http://sourcemaking.com/design_patterns
THANK YOU!
Ad

More Related Content

What's hot (20)

Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Ryan Mauger
 
Dci in PHP
Dci in PHPDci in PHP
Dci in PHP
Herman Peeren
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
Mohammad Imam Hossain
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
Amit Himani
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
Eric Satterwhite
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
Yurii Kotov
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
Divante
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
Mohammad Imam Hossain
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin development
Faruk Hossen
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
JimKellerES
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
Rana Ali
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
Michael Pustovit
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
eprafulla
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
Julie Iskander
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Marco Tusa
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
Josh Adell
 
What's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field APIWhat's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field API
Drupalize.Me
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
garbles
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Ryan Mauger
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
Amit Himani
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
Eric Satterwhite
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
Yurii Kotov
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
Divante
 
Jquery plugin development
Jquery plugin developmentJquery plugin development
Jquery plugin development
Faruk Hossen
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
JimKellerES
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
Rana Ali
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
Michael Pustovit
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
eprafulla
 
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Accessing Data Through Hibernate; What DBAs Should Tell Developers and Vice V...
Marco Tusa
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
Josh Adell
 
What's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field APIWhat's New in Drupal 8: Entity Field API
What's New in Drupal 8: Entity Field API
Drupalize.Me
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
garbles
 

Viewers also liked (13)

Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
melbournepatterns
 
Prototype Pattern
Prototype PatternPrototype Pattern
Prototype Pattern
Ider Zheng
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
Thaichor Seng
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Patterns in nature
Patterns in naturePatterns in nature
Patterns in nature
huntam
 
The Nature Of Patterns
The Nature Of PatternsThe Nature Of Patterns
The Nature Of Patterns
Nick Harrison
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentation
ISsoft
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
Piyush Mittal
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
Srikanth R Vaka
 
Prototype_pattern
Prototype_patternPrototype_pattern
Prototype_pattern
Iryney Baran
 
TYPES OF PATTERN AND ITS APPLICATION
TYPES OF PATTERN AND ITS APPLICATIONTYPES OF PATTERN AND ITS APPLICATION
TYPES OF PATTERN AND ITS APPLICATION
Praveen Kumar
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Prototype Pattern
Prototype PatternPrototype Pattern
Prototype Pattern
Ider Zheng
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
Thaichor Seng
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Patterns in nature
Patterns in naturePatterns in nature
Patterns in nature
huntam
 
The Nature Of Patterns
The Nature Of PatternsThe Nature Of Patterns
The Nature Of Patterns
Nick Harrison
 
Prototype presentation
Prototype presentationPrototype presentation
Prototype presentation
ISsoft
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
Piyush Mittal
 
TYPES OF PATTERN AND ITS APPLICATION
TYPES OF PATTERN AND ITS APPLICATIONTYPES OF PATTERN AND ITS APPLICATION
TYPES OF PATTERN AND ITS APPLICATION
Praveen Kumar
 
Design Patterns Illustrated
Design Patterns IllustratedDesign Patterns Illustrated
Design Patterns Illustrated
Herman Peeren
 
Ad

Similar to Design Patterns and Usage (20)

Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
Vasily Kartashov
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
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
SWIFTotter Solutions
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
Prabhjit Singh
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
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
mtoppa
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objects
Simone Gentili
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.
Juciellen Cabrera
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
Jalpesh Vasa
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
Dang Tuan
 
10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards10 PHP Design Patterns #burningkeyboards
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
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
SWIFTotter Solutions
 
5 Design Patterns Explained
5 Design Patterns Explained5 Design Patterns Explained
5 Design Patterns Explained
Prabhjit Singh
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
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
mtoppa
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objects
Simone Gentili
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.Does your code spark joy? Refactoring techniques to make your life easier.
Does your code spark joy? Refactoring techniques to make your life easier.
Juciellen Cabrera
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
Jalpesh Vasa
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
Dang Tuan
 
Ad

More from Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
Mindfire Solutions
 
diet management app
diet management appdiet management app
diet management app
Mindfire Solutions
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
Mindfire Solutions
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
Mindfire Solutions
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
Mindfire Solutions
 
ELMAH
ELMAHELMAH
ELMAH
Mindfire Solutions
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
Mindfire Solutions
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
Mindfire Solutions
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
Mindfire Solutions
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
Mindfire Solutions
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
Mindfire Solutions
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
Mindfire Solutions
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
Mindfire Solutions
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
Mindfire Solutions
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
Mindfire Solutions
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
Mindfire Solutions
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
Mindfire Solutions
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
Mindfire Solutions
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
Mindfire Solutions
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
Mindfire Solutions
 

Recently uploaded (20)

Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Microsoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptxMicrosoft Excel Core Points Training.pptx
Microsoft Excel Core Points Training.pptx
Mekonnen
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025DVDFab Crack FREE Download Latest Version 2025
DVDFab Crack FREE Download Latest Version 2025
younisnoman75
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game DevelopmentBest Practices for Collaborating with 3D Artists in Mobile Game Development
Best Practices for Collaborating with 3D Artists in Mobile Game Development
Juego Studios
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Full Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest VersionFull Cracked Resolume Arena Latest Version
Full Cracked Resolume Arena Latest Version
jonesmichealj2
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 

Design Patterns and Usage

  • 1. Design Patterns Usage and Application By Manas Ranjan Sahoo
  • 2. What is it? 1. 23 common problems best accepted solutions 1. Started at IBM 1994 1. Solutions can be successfully applied to right problems 1. Using DP the risk of solutions becomes zero 1. These are well thought and tested solutions 1. Solution templates for re-occurring programming challenges
  • 3. 1. A design pattern is a solution to common problems that have already been discovered, documented, and is in wide use 1. Don't think of patterns as data structures, or algorithms 1. Think as if your code as people sending messages, like sending letters, to each other 1. Each object is a 'person'. 1. The way that you'd organize the 'people' and the patterns they use to send messages to each other are the patterns 1. Patterns deals with relationships and interactions of classes and objects
  • 4. ● A good working knowledge of the patterns saves inventing your own solutions to well-known problems. ● It is analogous to abstract data types: every coder should know what a stack, list and queue are and recognize when it is appropriate to use them - they should not write code first and then say "Oh I could have just used a Stack there." ● You can alter a given class without changing the rest of the code that interacts with it. Why
  • 5. ● The key is to learn to identify the scenarios and problems which the patterns are meant to address. Then applying the pattern is simply a matter of using the right tool for the job. ● Patterns save time because we don’t have to solve a problem that’s already been solved. ● Design patterns have two major benefits. - They provide help us identifying a proven solution which facilitates the development of highly cohesive modules with minimal coupling. - They make communication between designers more efficient.
  • 6. Types ● Factory ● Singleton ● Delegate ● Decorator ● Strategy ● Observer ● Adapter ● State ● Iterator ● Front Controller ● MVC ● Active Record
  • 7. Factory Pattern ● Most Commonly used ● A class simply creates the object you want to use ● We can define a factory as a simple design pattern that give us a convenient way to instantiate objects. ● we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
  • 8. class Thing { public function do_something() { echo 'Hello PHPeople'; } } class Factory { public function create_thing() { return new Thing(); } } $factory = new Factory(); $thing = $factory->create_thing(); $thing->do_something();
  • 9. Singleton Pattern ● When designing web applications, we often need to allow access to one and only one instance of a particular class. ● These ensure there is a single class instance and that is global point of access for it.
  • 10. When to Use You use a singleton when you need to manage a shared resource. For instance a printer spooler. Your application should only have a single instance of the spooler in order to avoid conflicting request for the same resource. Useful when only one object is required across the system.
  • 11. class DatabaseConnection { private static $singleton_instance = null; private function construct__() { // private ensures // that this object is not created as a new intance // outside of this class. } public static function global_instance() { static $singleton_instance = null; if($singleton_instance === null) { $singleton_instance = new DatabaseConnection(); } return($singleton_instance); } public function exec_query($query) { print "Running query: " . $query; } }
  • 12. // We create a database instance by running the static function // which returns the singleton instance of the class $db_connection = DatabaseConnection::global_instance();
  • 13. Delegator Pattern In this an object, instead of performing one of its stated tasks, delegates that task to an associated helper object The helper object is known as a delegate. Delegate is given the responsibility to execute a task for the delegator.
  • 14. interface Printer { public function printline($subject); } class DelegatePrinter implements Printer { public function printline($subject) { print $subject; } } class Client { public function __construct() { $this->printer = new DelegatePrinter; } public function printData() { $this->printer->printline('Some string data'); } } $client = new Client; $client->printData();
  • 15. Decorator Pattern Its a pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class Decorator uses Delegation, it is a subset of delegation. Decorator works best when you want to take something that's working and have it do something else, but not change the interface at all Decorator is used to construct a complex object by using mechanism called Delegation
  • 16. class Book { private $title; public function __construct($title_in) { $this->title = $title_in; } public function getTitle() { return $this->title; } //we need to implement showtitle method here } class BookTitleDecorator { private $book; private $title; public function __construct(Book $bookobj) { $this->book = $bookobj; $this->title = $this->book->getTitle(); } public function showTitle() { return $this->title; } }
  • 17. include_once('Book.php'); include_once('BookTitleDecorator.php'); $DesignPatternBook = new Book("Design Patterns Book explaining Decorators"); $decorator = new BookTitleDecorator($DesignPatternBook); echo $decorator->showTitle();
  • 18. Strategy Pattern Here a context will choose the appropriate concrete extension of a class interface. Capture the abstraction in an interface, bury implementation details in derived classes. Strategy lets you change the guts of an object. Decorator lets you change the skin. Example - Mode of travel to reach Airport
  • 19. class StrategyContext { ///context for chosing extension private $strategy = NULL; public function __construct($strategy_id) { switch ($strategy_id) { case "A": $this->strategy = new StrategyA(); break; } } public function showBookTitle($book) { return $this->strategy->showTitle($book); } }
  • 20. interface StrategyInterface { //abstraction captured public function showTitle($bookobj); } class StrategyA implements StrategyInterface { //implementaion detail here public function showTitle($bookobj) { $title = $bookobj->getTitle(); return strtoupper ($title); } } class Book { private $title; function __construct($title) { $this->title = $title; } function getTitle() {return $this->title;} }
  • 21. $book = new Book('PHP for Cats'); $strategyContextA = new StrategyContext('A'); echo $strategyContextA->showBookTitle($book);
  • 22. Observer Pattern This is a design pattern in which an object, register multiple dependents, called observers, and notifies them automatically of any state changes Observers look for changes and do something Example - A newspaper and subscribers Its used when a state change in subject affects other objects, and you don't know how many objects need to be changed
  • 23. abstract class Publisher { abstract function attach(Observer $observer); abstract function detach(Observer $observer); abstract function notify(); } abstract class Observer { abstract function update(Publisher $subject_in); } class Account extends Publisher { public $status = NULL; public $_observers = array(); function attach(Observer $observer_in) { array_push($this->_observers, $observer_in); } function detach(Observer $observer_in) { $this->_observers = array_diff($this->_observers, array($observer_in)); } public function notify() { foreach($this->_observers as $obs) { $obs->update($this); } } }
  • 24. class Logger extends Observer { public function __construct() { } public function update(Publisher $pub) { //Update status in log table echo "Updating status in log table.n"; } } include_once('Account.php'); include_once('Logger.php'); $account = new Account(); $logger = new Logger(); $account->attach($logger); $account->status = "Expired"; $account->notify();
  • 25. Adapter Pattern This pattern is used when we want to convert the interface one class to an interface which can be used by another class. whenever there is a problem that requires the continued stability of the main platform and does not disrupt the existing application flow, the Adapter Design Pattern could be used in developing the solution. Real-world examples might be a language translator, or a mobile charger. It involves a single class called adapter which is responsible for communication between 2 incompatible classes.
  • 26. class Book { private $title; private $price; function __construct($title, $price) { $this->title = $title; $this->price = $price; } function getTitle() { return $this->title; } function getPrice() { return $this->price; } }
  • 27. class BookAdapter { private $book; function __construct(Book $bookobj) { $this->book = $bookobj; } function getTitleAndPrice() { return $this->book->getTitle().' - '.$this->book->getPrice(); } } $book = new Book("Design Patterns", "$125"); $bookAdapter = new BookAdapter($book); print('Title and Price: '.$bookAdapter->getTitleAndPrice());
  • 28. State Pattern All our final decisions are made in a state of mind that is not going to last — Marcel Proust The purpose is to allow an object to change its behavior when the state changes. It is used to allow an object to changes it’s behaviour when it’s internal state changes A class will change it's behavior when circumstances change.
  • 29. interface State { function press(StopWatchContext $context); } class StopState implements State { public function press(StopWatchContext $context) { $time = (microtime(TRUE) * 1000) - $context->getStartTime(); printf("The stop watch is stopped. [Time] %d MS <br>", $time);; $context->setState($context->getStartState()); // State is changed here } } class StartState implements State { public function press(StopWatchContext $context) { echo "The stop watch is running..<br>"; $context->setState($context->getStopState()); // State is changed here } } class ResetState implements State { public function press(StopWatchContext $context) { echo "The stop watch is reset. <br>"; $context->setStartTime(microtime(TRUE) * 1000); $context->setState($context->getStartState()); // State is changed here } }
  • 30. class StopWatchContext { private $state; private $startTime; private $startState; private $stopState; private $resetState; public function __construct() { $this->setStartTime(); $this->startState = new StartState(); $this->stopState = new StopState(); $this->resetState = new ResetState(); $this->state = $this->startState; } public function setState(State $state) { $this->state = $state; } public function pressButton() { $this->state->press($this); }
  • 31. public function resetButton() { $this->setState(new ResetState()); $this->pressButton(); } public function getStartTime() { return $this->startTime; } public function setStartTime() { $this->startTime = microtime(TRUE) * 1000; } public function getStartState() { return $this->startState; } public function getStopState() { return $this->stopState; } public function getResetState() { return $this->resetState; } }
  • 32. $timer = new StopWatchContext(); $timer->pressButton(); //started usleep(1200 * 1000); // sleeping 1.2 seconds $timer->pressButton(); //stopped $timer->pressButton(); //started usleep(2000 * 1000); //sleeping 1.7 seconds (3200 MS) $timer->pressButton();//stopped $timer->resetButton(); //reset $timer->pressButton();//started sleep(2);//sleeping 2 seconds $timer->pressButton(); //stopped
  • 33. Iterator Pattern Not all objects are the same when it comes to looping. It helps construct objects that can provide a single standard interface to loop or iterate through any type of countable data. When dealing with countable data that needs to be traversed, creating an object based on the Iterator Design Pattern is the best solution.
  • 34. class AddressDisplay { private $addressType; private $addressText; public function setAddressType($addressType) { $this->addressType = $addressType; } public function getAddressType() { return $this->addressType; } public function setAddressText($addressText) { $this->addressText = $addressText; } public function getAddressText() { return $this->addressText; } }
  • 35. class EmailAddress { private $emailAddress; public function getEmailAddress() { return $this->emailAddress; } public function setEmailAddress($address) { $this->emailAddress = $address; } } class PhysicalAddress { private $streetAddress; private $city; private $state; private $postalCode;
  • 36. public function __construct($streetAddress, $city, $state, $postalCode) { $this->streetAddress = $streetAddress; $this->city = $city; $this->state = $state; $this->postalCode = $postalCode; } public function getStreetAddress() { return $this->streetAddress; } public function getCity() { return $this->city; } public function getState() { return $this->state; } public function getPostalCode() { return $this->postalCode; } public function setStreetAddress($streetAddress) { $this->streetAddress = $streetAddress; } public function setCity($city) { $this->city = $city; }
  • 37. public function setState($state) { $this->state = $state; } public function setPostalCode($postalCode) { $this->postalCode = $postalCode; } } class PersonAddressIterator implements AddressIterator { private $emailAddresses; private $physicalAddresses; private $position; public function __construct($emailAddresses) { $this->emailAddresses = $emailAddresses; $this->position = 0; }
  • 38. public function hasNext() { if ($this->position >= count($this->emailAddresses) || $this->emailAddresses[$this->position] == null) { return false; } else { return true; }} public function next() { $item = $this->emailAddresses[$this->position]; $this->position = $this->position + 1; return $item; } }
  • 39. Front Controller Pattern It relates to the design of web applications. It "provides a centralized entry point for handling requests All request send to the application are processed with it, which then redirects each request to the corresponding Action Controller Example: The login.php on specific request instantiate further objects and call methods to handle the particular task(s) required. Yii, CakePHP, Laravel, Symfony, CodeIgniter and Zend Framework, Magento, MVC frameworks uses front controller
  • 40. MVC Pattern Its a for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from users. The model directly manages the data, logic and rules of the application. A view can be any output representation of information. The controller, accepts input and converts it to commands for the model or view.
  • 41. Active Record Pattern This is pattern found in software that stores its data in relational databases. The interface of the object using this pattern would include functions such as Insert, Update, and Delete operations We can say this as an approach to accessing data in a database. Laravel contains an ORM called 'Eloquent' which implements the active record pattern. CakePHP's ORM implements the active record pattern. A database table is wrapped into a class. An object instance is tied to a single row in the table.
  • 42. Magento Patterns MVC Magento leverages xml to drive the configuration and actions of the application on top of the regular Model-View-Controller architecture. Front Controller Magneto has a single entry point (index.php) for all of it's requests. Factory The Factory Method is used to instantiate classes in Magento. Singleton In magento Singleton pattern is instantiated for Blocks and Classes.
  • 43. Registry Its basically a pattern that allows any object or data to be available in a public global scope for any resource to use. Object Pool The Object Pool Pattern keeps objects ready for use over and over again instead of re-instantiating them and destroying them once finished. Iterator Magento allows an object traverse through the elements of another class. The core/resource_iterator model allows you to get the collection item data one by one executing corresponding SQL query. Module Magneto is based on modular programming and emphasizes the grouping of functionality of a program into independent, interchangeable modules.
  • 44. Observer Magento uses observer pattern by providing event listeners through which other components of the application can "hook" into this event listener and execute their code.
  • 45. References http://www.wrox.com/WileyCDA/WroxTitle/Professional-PHP-Design- Patterns.productCd-0470496703.html http://www.phptherightway.com/pages/Design-Patterns.html http://www.fluffycat.com/PHP-Design-Patterns/ http://en.wikipedia.org/wiki/Design_Patterns http://www.oodesign.com http://sourcemaking.com/design_patterns