DesignPatternsPHP / DesignPatternsPHP

Sample code for several design patterns in PHP 8.x

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How is visitor possible in PHP?

douma opened this issue · comments

commented

Visitor uses method overloading, dynamic dispatch, which is impossible in PHP. The only use for visitor is if languages do not support double dispatch, but they really do need to support method overloading.

In your example there is no way to switch methods based on the parameters. So the accept method becomes low level, while it is supposed to be high level. The accept methods job is to convert the static compile time (or as defined in the code)- type to the dynamic run type.

Visitor is used to define relationships between concrete types. This is possible in PHP, by using the dynamic features of the language, such as magic methods and variable functions.

No thats not correct. There is a dependency on the type of the visited class, so method overloading is not necessary. Visitor would only use method overloading to dispatch the method calls to visit(), but there is a dependency on the type of the Role thats reflected in the method signature: visit(Group group).

In PHP, the method signature just expresses the same thing, only that the method signature changes to this: visitGroup(Group group). If there is a new class to be visited, you would have to implement a new visit() anyway (which is by far the greatest downside to this pattern). In PHP, you would also have to change the interface, which I think is not that bad though as the interface would show at first glance all the classes that can be visited.

Also, there are a lot of (OO-) languages that don't support method overloading, but why should you not use this pattern? Have a look at the Python example in Wikipedia: https://en.wikipedia.org/w/index.php?title=Visitor_pattern&section=27#Python_example

commented

So what do you claim? You have implemented double dispatch? This is simply not possible in PHP.

The visitor takes the instance reference as input, and implements the goal through double dispatch.
https://en.wikipedia.org/wiki/Visitor_pattern

In your case you have provided a sort of strategy pattern. Looking at the UML the pattern you have created is not that different, but you miss the fact that languages are different. I think you miss the entire intend of why the visitor pattern was created in the first place.

I didn't claim I implemented double dispatch. And it is not a necessary prerequisite to implement the Visitor pattern. In fact even the example by Gang Of Four does not use double dispatch.

And I do not miss the fact that languages are different, but you are. I provided you with the Python example that does not use double dispatch either and is just fine.