This package provides a visitor pattern implementation.
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
Via Composer
$ composer require thrashzone13/visitor
Consider having an array of different kinds of shapes
$shapes = [
new Circle(radius: 10),
new Rectangle(width: 15, height: 20),
new Rectangle(width: 10, height: 14),
new Square(side: 16)
];
Let's say the intention is to calculate their area and sum them up. There can be a visitor which does the calculation regarding the type of the received instance
$visitor = (new Visitor)
->add(fn(Circle $circle) => pi() * $circle->getRadius() * $circle->getRadius())
->add(fn(Square $square) => $square->getSide() * $square->getSide())
->add(fn(Rectangle $rectangle) => $rectangle->getWidth() * $rectangle->getHeight());
Now it's ready to use!
$totalArea = 0;
foreach ($shapes as $shape) {
$totalArea += $visitor->visit($circle);
}
The MIT License (MIT). Please see License File for more information.