Current Location: Home> Latest Articles> PHP Decorator Pattern Guide: How to Dynamically Add Functionality

PHP Decorator Pattern Guide: How to Dynamically Add Functionality

M66 2025-09-21

The Decorator Pattern in PHP

The decorator pattern allows you to dynamically add new functionality to an object without changing the original object. This is achieved by creating a wrapper class that attaches itself to the original object and provides additional functionality. One of the key features of the decorator pattern is that it allows you to dynamically combine multiple decorators, making object functionality more flexible.

Practical Example: Adding Tags to User Input Strings

Let's look at a practical example: suppose we have a class for generating HTML tags, and we need a way to dynamically add tags to a string provided by the user. Using the decorator pattern, we can efficiently achieve this requirement:

<?php
// Create the tag wrapper class
class TagDecorator {
    protected $tag;
    protected $object;

    public function __construct($tag, $object) {
        $this->tag = $tag;
        $this->object = $object;
    }

    public function __toString() {
        return "<{$this->tag}>{$this->object}</{$this->tag}>";
    }
}

// Create the original object
$input = 'Hello, world!';

// Use the wrapper class to add tags
$boldDecorator = new TagDecorator('b', $input);
$italicDecorator = new TagDecorator('i', $boldDecorator);

// Display the string with tags
echo $italicDecorator;

// Output:
// <b><i>Hello, world!</i></b>
?>

In this example, the TagDecorator class acts as a wrapper that attaches HTML tags to the original input string. By wrapping the decorator around the existing object, we can easily add extra functionality without affecting the original object's code.

Advantages of the Decorator Pattern

One major advantage of the decorator pattern is its flexibility. You can dynamically add or remove functionality as needed without modifying the structure of the original object. This is particularly useful for applications that need to dynamically extend functionality at runtime.

Important Considerations

  • The decorator class should implement the same interface as the wrapped object or inherit from the wrapped object.
  • The decorator pattern can be easily combined to create objects with complex functionalities.
  • Decorators are reversible, meaning you can remove them when they are no longer needed.

With the above explanation, you should now understand the PHP decorator pattern and how to apply it in real-world projects. This design pattern can help you manage the functionality extension of objects in a more flexible way.