Implementing the Visitor Pattern requires the ability to dynamically determine the type of the Visitor and the type of the “Element” (aka: object receiving the visitor).
In PHP (>= 5.0.0), this can easily be achieved with the get_class()
function as we will see shortly.
Let’s start by looking at how the Visitor Pattern will look within user code;
$updateVisitor = new UpdateVisitor(); $deleteVisitor = new DeleteVisitor(); $element = new Foo(); $element->visit($updateVisitor); $element->visit($deleteVisitor);
Looking at the UpdateVisitor
class, we want the visitFoo()
function to be called;
interface Visitor { } class UpdateVisitor implements Visitor { public function visitFoo(Foo $theElement) { // ... } }
You may already be (correctly) thinking “Why not just call $updateVisitor->visitFoo($element)
directly?”.
Continue reading