Expanding the Application Range of Visitor Objects in PHP 5 - Visiting software users isn't boring at all: creating a concrete visitor class
(Page 4 of 5 )
It's quite possible that you're wondering how a visitor class can be coded to allow all its properties to be retrieved without having to use its accessing methods. Well, fortunately your question can be answered in two easy steps: first, I'll define the generic structure of a visitor class, and then I'll create a subclass from it.
Indeed, this sounds logical, thus in accordance with this approach, below I listed the signature of the abstract "Visitor" class:
// define abstract 'Visitor' class
abstract class Visitor{
abstract function visitSoftwareUser(SoftwareUser $softwareUser);
}
That's all I need to define the generic model of a visitor. Notice the declaration of the abstract "visitSoftwareUser()" method, which will accept as input argument the visited object, in this case represented by an instance of the "SoftwareUser" class.
Now that you know how the prior abstract class looks, it's time to implement its visiting method. That said, here is the corresponding definition of the entirely new "SoftwareUserVisitor" subclass:
// define concrete 'SoftwareUserVisitor' class
class SoftwareUserVisitor extends Visitor{
private $softwareUserInfo=array();
// obtain user information as array
public function visitSoftwareUser(SoftwareUser $softwareUser){
$this->softwareUserInfo['userid']=$softwareUser-
>getUserID();
$this->softwareUserInfo['firstname']=$softwareUser-
>getFirstName();
$this->softwareUserInfo['lastname']=$softwareUser-
>getLastName();
$this->softwareUserInfo['postaladdress']=$softwareUser-
>getPostalAddress();
//$this->softwareUserInfo['email']=$softwareUser-
>getEmail();
$this->softwareUserInfo['software']=$softwareUser-
>getPreferredSoftware();
}
public function getSoftwareUserInfo(){
return $this->softwareUserInfo;
}
}
As you can see, now this brand new class offers a concrete implementation for its "visitSoftwareUser()" method. It's clear to see here how all the properties of an object of type "SoftwareUser" are retrieved by the visitor in question, and additionally, to make things even easier, they're stored in an array. Short and understandable!
At this level, after defining the two classes that allow the implementation of the visitor pattern, that is, the visited and visitor classes respectively, it's a good time to watch them together in action.
Not surprisingly, that's exactly the subject that I'll cover in the next few lines. Keep reading; I'll be waiting for you in the following section.
Next: Putting the classes to work together: seeing the visitor object in action >>
More PHP Articles
More By Alejandro Gervasio