search
HomeBackend DevelopmentPHP TutorialDecorator Pattern: Unleashing the Power of Design Patterns

Decorator Pattern: Unleashing the Power of Design Patterns

Earlier in this series, we explored the facade and adapter design patterns in this series. Using Facade we can simplify large systems and by implementing adapters we can stay safe when using external APIs and classes. Now we will introduce the decorator design pattern, which also falls under the category of structural patterns.

When we just want to give some extra responsibilities to the base class, we can use the decorator pattern. This design pattern is a great alternative to subclassing functionality, extending functionality and having some added advantages.

question

If you are confused and think that we can also achieve the same functionality by subclassing functionality, then let me show you some code examples that will clear your confusion and make you love the decorator pattern.

I will give an example of a class responsible for generating email content. In the next code block, as you can see, this class generates the email content just fine without any modifications.

class eMailBody {
    private $header = 'This is email header';
	private $footer = 'This is email Footer';
	public $body = '';

	public function loadBody() {
		$this->body .= "This is Main Email body.<br />";
	}
}

We know Christmas is coming, so let’s say I want to greet my readers in my next newsletter email. So I have to add a message in the body of the email with an image that looks good.

To do this, I could edit directly in my email class, but I really don't want to do that. So I can implement inheritance to achieve the same effect. I create a separate subclass of the main email body class:

class christmasEmail extends eMailBody {
    public function loadBody() {
		parent::loadBody();
		$this->body .= "Added Content for Xmas<br />";
	}
}

$christmasEmail = new christmasEmail();
$christmasEmail->loadBody();
echo $christmasEmail->body;

So I finished my code and after a few days I want to send an email with new year wishes. We can use the same approach as Christmas.

class newYearEmail extends eMailBody {
    public function loadBody() {
		parent::loadBody();
		$this->body .= "Added Content for New Year<br />";
	}
}

$newYearEmail = new newYearEmail();
$newYearEmail->loadBody();
echo $newYearEmail->body;

Everything went smoothly and there were no problems. Now, let's say I forgot to greet my visitors on these two occasions (Christmas and New Year) and I want to send both greetings in one email without modifying any code in the base class.

Your mind is immediately filled with the following questions: Will subclassing and inheritance help here? I'm in favor of doing this, but we need to use extra/unnecessary code to achieve this. We can use traits to achieve something similar to multiple inheritance.

solution

The problems we discussed in the previous section can be solved by implementing the decorator pattern.

According to Wikipedia:

The Decorator pattern (also known as Wrapper, an alternative nomenclature shared with the Adapter pattern) is a design pattern that allows static or dynamic addition of behavior to a single object without affecting the behavior of other objects. Same class.

In the previous section, we have seen that we can extend functionality/behavior using a subclass, but when it comes to adding multiple functionality/behavior, it becomes verbose and complex. This is where we should use the decorator pattern.

interface

interface eMailBody {
    public function loadBody();
}

This is a simple interface used to ensure that certain classes must implement the required methods.

Main Email Class

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

This is the main class that generates the default body of an email, I usually use it to send emails. However, what I need is to modify the body content based on certain occasions but not change the main email class.

Main Decorator

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

This is our main decorator class, which holds a reference to our main email class and changes its behavior as needed. Here we define an abstract method, loadBody, which the sub-decorator needs to implement to change the behavior.

Sub-decorator

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

}

Here we have created two subclasses of the main decorator that actually perform behavior changes on our main email class.

Wrap everything together

We have created all the required elements. All we need to do is use our code and enjoy.

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

}

Now we will use this decorator class in various ways as needed:

/*
 *  Normal Email
 */

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

We can see that now we have changed the body of the email without modifying the main email class.

in conclusion

Every application we have requires some kind of changes and/or improvements on a regular basis. So in this case we can implement the decorator design pattern which will ultimately improve the code quality and make our code more scalable.

I tried my best to explain the decorator pattern to you, but if you have any other comments or questions, please feel free to add them to the feed below.

The above is the detailed content of Decorator Pattern: Unleashing the Power of Design Patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor