alcamo / decorator
Base trait and class to create decorators
Installs: 23
Dependents: 2
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/alcamo/decorator
Requires
- php: 7.3 - 8.0
- alcamo/exception: ^0.1
Requires (Dev)
- php-ds/php-ds: ^1.3
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: 3.*
README
use alcamo\decorator\Decorator;
use Ds\Set;
class SetWithSum extends Decorator implements \Countable, \IteratorAggregate
{
public function __construct($values)
{
parent::__construct(new Set($values));
}
public function getSum(): int
{
$result = 0;
foreach ($this as $value) {
$result += $value;
}
return $result;
}
}
$set = new SetWithSum([ 42, 42, 7]);
echo "Count: " . count($set) . "\n";
echo "Sum: " . $set->getSum() . "\n";
This will output:
Count: 2
Sum: 49
Overview
The trait DecoratorTrait implements the Decorator
pattern for an
arbitrary object. The class Decorator uses this trait.
As in the example above, this can be used to create a class that adds functionality to a class when creating a derived class is not possible.
All functionality of the enclosed object is exposed by the decorator so that the decorator behaves just as the enclosed object, supporting, for instance, the Countable, Iterator or ArrayAccess interface.
The trait MultiDecoratedTrait offers a means to add multiple
decorators to an object, indexed by their class
nane. MultiDecoratedArrayAccessTrait is buil on top of this and
allows to access the decorators via ArrayAccess methods.
See the doxygen documentation for details.