design patterns in php

33
Design Patterns in PHP Jason Straughan - Grok Interactive, LLC

Upload: jason-straughan

Post on 10-May-2015

1.672 views

Category:

Technology


3 download

DESCRIPTION

Using common design patterns in PHP - Talk originally given at Geekdom in San Antonio, Texas, October 10, 2013

TRANSCRIPT

Page 1: Design patterns in PHP

Design Patterns in PHPJason Straughan - Grok Interactive, LLC

Page 2: Design patterns in PHP

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.

Page 3: Design patterns in PHP

What are design patterns?

Design patterns are concepts and best practices for solving common software

development problems.

Page 4: Design patterns in PHP

When to useYou already are using them.

To solve common problems.

To express architecture or solutions.

Recognize in existing code.

Page 5: Design patterns in PHP

How to useNot plug-and-play.

Implement as needed.

Use in frameworks and libraries.

Impress your friends.

Page 6: Design patterns in PHP

Common Patterns in PHP● Factory● Singleton● Delegate● Decorator● Strategy● Observer

● Adapter● State● Iterator● Front Controller● MVC● Active Record

Page 7: Design patterns in PHP

The Factory PatternCreates objects without having to instantiate the classes directly.

Factories create objects.

Page 8: Design patterns in PHP

When to use theFactory Pattern

Keep DRY when complex object creation needs to be reusable.

Encapsulate several objects or steps into new object creation.

Page 9: Design patterns in PHP

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'

Page 10: Design patterns in PHP

Example of a Factory Patternclass 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');

Page 11: Design patterns in PHP

The Singleton PatternCreates 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.

Page 12: Design patterns in PHP

When to use theSingleton Pattern

Require only one instance of an class.

Need only one connection to a server.

Page 13: Design patterns in PHP

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;

}

}

Page 14: Design patterns in PHP

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() {}

Page 15: Design patterns in PHP

Use associated objects to perform duties to complete tasks.

Delegation of tasks to helpers based on needs.

The Delegate Pattern

Page 16: Design patterns in PHP

When to use theDelegate Pattern

Object uses functionality in other classes.

Remove coupling to reusable code or abstract logic and tasks.

Page 17: Design patterns in PHP

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';

}

}

Page 18: Design patterns in PHP

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

Page 19: Design patterns in PHP

The Decorator Pattern

Decorators add functionality to an object without changing the object’s behavior.

Page 20: Design patterns in PHP

When to use theDecorator 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.

Page 21: Design patterns in PHP

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'

Page 22: Design patterns in PHP

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'

Page 23: Design patterns in PHP

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.

Page 24: Design patterns in PHP

When to use theStrategy Pattern

Criteria based data manipulation.

● Search result ranking● Weighted Voting● A/B Testing● Environment based decisions● Platform specific code

Page 25: Design patterns in PHP

Example of a Strategy Pattern

switch ($message_type) {

case 'email':

// Send Email

// Lots of code

break;

case 'twitter':

// Send Tweet

// More code here

break;

}

Page 26: Design patterns in PHP

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');

Page 27: Design patterns in PHP

Objects (subjects) register other objects (observers) that react to state changes of their subject.

Observers look for changes and do something.

The Observer Pattern

Page 28: Design patterns in PHP

When to use theObserver PatternState changes of an object affect other objects or datasets.

● Event handling● Data persistence● Logging

Page 29: Design patterns in PHP

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 )

}

Page 30: Design patterns in PHP

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'

Page 31: Design patterns in PHP

Review

Design Pattern are:● Reusable concepts● Best practice solutions● Tried and true methods

Page 32: Design patterns in PHP

Continuing Education

Design Patterns: Elements of Reusable Object-Oriented SoftwareErich Gamma, Richard Helm, Ralph Johnson and John Vlissides

Code and Slides provided onlinehttps://github.com/GrokInteractive/php_design_patterns_talk

Page 33: Design patterns in PHP

?>