PHP utilizes classes and interfaces to implement the decorator pattern. In object-oriented design, a class defines a user-defined datatype, encapsulating both properties and methods.
On the other hand, an interface in PHP serves as a contract for classes, specifying a set of methods that implementing classes must adhere to. It is declared using the interface keyword.
Here’s the basic syntax for defining an interface in PHP:
interface MyInterface {
// Method declarations
public function method1();
public function method2($param);
}
Example of a Decorator in PHP:
Certainly! Here’s an example of the decorator pattern in PHP. In this example, let’s create a simple TextFormatter interface and a concrete class PlainTextFormatter. We’ll then implement two decorators, BoldTextFormatter and ItalicTextFormatter, to demonstrate how decorators can enhance the behavior of the base component:
<?php
// Component interface
interface TextFormatter {
public function format(string $text): string;
}
// ConcreteComponent
class PlainTextFormatter implements TextFormatter {
public function format(string $text): string {
return $text;
}
}
// Decorator
abstract class TextDecorator implements TextFormatter {
protected $textFormatter;
public function __construct(TextFormatter $textFormatter) {
$this->textFormatter = $textFormatter;
}
public function format(string $text): string {
return $this->textFormatter->format($text);
}
}
// ConcreteDecorator
class BoldTextFormatter extends TextDecorator {
public function format(string $text): string {
return '' . parent::format($text) . '';
}
}
// ConcreteDecorator
class ItalicTextFormatter extends TextDecorator {
public function format(string $text): string {
return '' . parent::format($text) . '';
}
}
// Usage
$plainTextFormatter = new PlainTextFormatter();
echo "Plain Text: " . $plainTextFormatter->format("Hello, World!") . PHP_EOL;
$boldTextFormatter = new BoldTextFormatter($plainTextFormatter);
echo "Bold Text: " . $boldTextFormatter->format("Hello, World!") . PHP_EOL;
$italicTextFormatter = new ItalicTextFormatter($plainTextFormatter);
echo "Italic Text: " . $italicTextFormatter->format("Hello, World!") . PHP_EOL;
$boldItalicTextFormatter = new BoldTextFormatter($italicTextFormatter);
echo "Bold and Italic Text: " . $boldItalicTextFormatter->format("Hello, World!") . PHP_EOL;
?>
In the above example:
- TextFormatter is the component interface representing the base object that can be decorated.
- PlainTextFormatter is the concrete component implementing the TextFormatter interface.
- TextDecorator is the abstract decorator class that extends the TextFormatter interface and contains a reference to a TextFormatter object.
- BoldTextFormatter and ItalicTextFormatter are concrete decorator classes that extend TextDecorator and add specific formatting functionalities to the base text.