HomePHP Page 3 - Introducing Visitor Objects in PHP 5
Defining another sample class - PHP
Although the article’s title may seem a bit intimidating, the truth is that things are much simpler than you think. Like many other programming languages, PHP also allows you to construct and use visitor objects with minor hassles. But, before I go deeper into the subject, first let’s ask ourselves the following question: what are visitor objects, after all?
As I expressed earlier, I want to expand the practicality of the previous example by coding another sample class, which also accepts a visitor object. In this case, this new class is called "VisitedFile," and its signature is as follows:
// extend 'VisitedFile' class from abstract 'VisitedData' class class VisitedFile extends VisitedData{ private $filePath; public function __construct ($filePath='default_path/data.txt'){ $this->filePath=$filePath; } // add new line to data file public function addLine($line){ if(!$fp=fopen($this->filePath,'a+')){ throw new Exception('Error opening data file'); } fwrite($fp,$line."n"); fclose($fp); } // get file size public function getSize(){ if(!$size=filesize($this->filePath)){ throw new Exception('Error determining size of data file'); } return $size; } // get number of file lines public function getNumLines(){ if(!$numLines=count(file($this->filePath))){ throw new Exception('Error determining number of lines for data file'); } return $numLines; } // accepts 'visitator' object and call 'visitFile()' method public function acceptVisitator(Visitator $visitator){ $visitator->visitFile($this); } }
As shown above, the functionality of the new "VisitedFile" class is only limited to saving plain strings to a given text file. However, my intention here is that you pay attention to the respective "acceptVisitator()" method, since it's closely similar to the previous one that you learned in the past section.
Also, on this occasion, the visitor will call its visiting method, and pass to it the visited object, with the purpose of getting additional information about it. As I said before, this model of object interaction is practically identical for all the cases where the visitor pattern is implemented. I hope you'll have no problem grasping this concept.
Okay, at this point you learned how to create two subclasses that accept visitor objects, but... how can these visitors be created? Do you have any clue about that? Well, to dissipate any possible questions, over the course of the next section, I'll show you how to define the structure of visitor objects.
To learn how this will be done, click on the link below and continue reading.