Pages

Search This Blog

Tuesday 16 June 2015

Implementation Of Decorator Design Pattern in PHP (Practical Example)

<?php

/*
 *
 * @Author: Zuhair Mirza
 * @Implementation Of Decorator Design Pattern in PHP (Practical Example)
 * @Date : 16-June-2015
 * @Defination  :  The decorator pattern (also known as Wrapper, an alternative naming
 * shared with the Adapter pattern) is a design 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.
 *
 * Every application we have needs some sort of alteration and/or improvements at uniform intervals.
 * So in such a case we can implement the decorator design pattern and it will ultimately improve
 * code quality and make our code more extendable.
 */


interface eMailBody {
    public function loadBody();
}

class eMail implements eMailBody {
    public function loadBody() {
        echo "This is Main Email body.<br />";
    }
}

abstract class emailBodyDecorator implements eMailBody {
   
    protected $emailBody;
   
    public function __construct(eMailBody $emailBody) {
        $this->emailBody = $emailBody;
    }
   
    abstract public function loadBody();
   
}

class christmasEmailBody extends emailBodyDecorator {
   
    public function loadBody() {
       
        echo 'This is Extra Content for Christmas<br />';
        $this->emailBody->loadBody();
       
    }
   
}

class newYearEmailBody extends emailBodyDecorator {

    public function loadBody() {
       
        echo 'This is Extra Content for New Year.<br />';
        $this->emailBody->loadBody();
       
    }

}

/*
 *  Running Code
 */

$email = new eMail();
$email->loadBody();

// Output
//This is Main Email body.


/*
 *  Email with Xmas Greetings
 */

$email = new eMail();
$email = new christmasEmailBody($email);
$email->loadBody();

// Output
//This is Extra Content for Christmas
//This is Main Email body.

/*
 *  Email with New Year Greetings
 */

$email = new eMail();
$email = new newYearEmailBody($email);
$email->loadBody();


// Output
//This is Extra Content for New Year.
//This is Main Email body.

/*
 *  Email with Xmas and New Year Greetings
 */

$email = new eMail();
$email = new christmasEmailBody($email);
$email = new newYearEmailBody($email);
$email->loadBody();

// Output
//This is Extra Content for New Year.
//This is Extra Content for Christmas
//This is Main Email body.

No comments:

Post a Comment