thrashzone13 / visitor
Simple implementation of visitor design pattern
V1.0.1
2024-12-23 11:47 UTC
Requires
- php: ^7.2|^8.0
Requires (Dev)
- phpunit/phpunit: 11.2.8
- squizlabs/php_codesniffer: ^3.0
This package is auto-updated.
Last update: 2025-06-23 12:50:55 UTC
README
This package provides a visitor pattern implementation.
Visitor Pattern
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
Install
Via Composer
$ composer require thrashzone13/visitor
Usage
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($shape); }
License
The MIT License (MIT). Please see License File for more information.