Example 2

Use case: We need to create a text filtering system. Given a string we should be able to strip out any html tags or any other malicious code in that string. The consumer of that system could use any or all of the filters available to him.

<?php

interface Filter
{
    public function formatText(string $text): string;
}


// The base class that we will apply the decorators to.

class RawText implements Filter
{

    public function formatText(string $text): string
    {
        // The base class returns the string without any filtering.
        return $text;
    }
}

And the filter decorators

<?php

abstract class BaseFilter implements Filter
{
    protected $formatter;

    public function __construct(Filter $formatter)
    {
        $this->formatter = $formatter;
    }
}

class StripTagsFilter extends BaseFilter
{
    public function formatText(string $text): string
    {
        return $this->formatter->formatText($text). ', now has its tags stripped out';
    }
}

class MaliciousTextFilter extends BaseFilter
{
    public function formatText(string $text): string
    {
        return $this->formatter->formatText($text). ', now has any malicious text stripped out';
    }
}

Now let's see how the client should handle the filtering of a given text.

<?php

$text = new RawText();
$text = new StripTagsFilter($text);
$text = new MaliciousTextFilter($text);

echo $text->formatText('hey there string') . PHP_EOL;

// Output
// hey there string, now has its tags stripped out, now has any malicious text stripped out