HomePHP Page 2 - Expanding the Application Range of Visitor Objects in PHP 5
Visiting users isn't a bad idea after all: setting up a new practical example - PHP
Has your career as PHP developer led you to learn more about the most popular design patterns? If it has, then this series may help you get a better grounding in them. Welcome to the second installment of the series “Introducing Visitor Objects in PHP 5.” Made up of three articles, this series introduces the key points of how to apply the visitor pattern in PHP, and emphasizes the practical side of the topic by walking you though copious hands-on examples.
The visitor pattern (among others) reveals its real power when it's presented within the environment of a practical situation. Therefore I'm going to set up another example which will illustrate yet another case where this pattern can be applied.
To begin with, I'll define a highly generic "User" class, and next create a sub class from it. This child class will expose a concrete method that will allow a visitor object to inspect and obtain all its visible properties in only one step. Sounds quite good, right? Considering this propitious scenario, take a look at the abstract class defined below, which represents the generic model of a hypothetical user:
// define abstract class 'User' abstract class User{ private $userID; private $firstName; private $lastName; private $postalAddress; private $email; abstract function setUserID($userID); abstract function setFirstName($firstName); abstract function setLastName($lastName); abstract function setPostalAddress($postalAddress); abstract function setEmail($email); abstract function getUserID(); abstract function getFirstName(); abstract function getLastName(); abstract function getPostalAddress(); abstract function getEmail(); abstract function acceptVisitor(Visitor $visitor); }
As you can appreciate, above I created a generic model of a typical user. The class also has some abstract methods, which are handy for accessing and retrieving the properties of this user, such as First Name, Last Name, Postal Address and so forth. Of course, aside from the regular accessors and modifiers, there's one method that deserves special attention. It is the "acceptVisitor()" method, which will be responsible for accepting a visitor, in order to inspect all the properties that belongs to the visited object.
Now that I have shown you the generic structure of the "User" class, I'll derive a child class from it which implements concretely all the abstract methods declared before.
Of course, all these tasks will be performed over the course of the next section, thus keep reading to learn how this will be achieved.