Structural patterns
In this section, we will take a look at a structural pattern: the decorator pattern.
The decorator pattern
The decorator pattern is a simple one. It allows us to add new behavior to object instances without affecting other instances of the same class. It basically acts as a decorating wrapper around our object. We can imagine a simple use case with a Logger class instance, where we have a simple logger class that we would like to occasionally decorate, or wrap into a more specific error, warning, and notice level logger.
The following example demonstrates a possible decorator pattern implementation:
<?php
interface LoggerInterface
{
public function log($message);
}
class Logger implements LoggerInterface
{
public function log($message)
{
file_put_contents('app.log', $message . PHP_EOL, FILE_APPEND);
}
}
abstract class LoggerDecorator implements LoggerInterface
{
protected $logger;
public function __construct(Logger $logger)
{
...