Processing File Data with Template Classes in PHP 5 - Creating a simple template class
(Page 3 of 5 )
In consonance with the concepts that I deployed in the previous section, after defining the file processing class that you saw before, the next step to take here involves building the structure of a template class. The class will be responsible of setting up a base algorithm for displaying some data fetched from a specified target file.
However, I think that the true functionality of this template class will be understood best if I first show you its corresponding signature. It is as follows:
// define abstract 'FileTemplate' class
abstract class FileTemplate{
// this method setup the generic algorithm to format file
contents
public final function displayFormattedFileContents
($fileProcessor){
$output='';
if($this->getFileSize($fileProcessor)==NULL){
throw new Exception('Size of data file could not be
retrieved!');
}
$output.=$this->getFileSize($fileProcessor).$this-
>getFormattedFileContents($fileProcessor);
return $output;
}
// this method setup the generic algorithm to get the size of
data file
public function getFileSize($fileProcessor){
return NULL;
}
// this method has not implementation (implemented in the
subclasses)
public function getFormattedFileContents(){}
}
If you examine the definition that corresponds to the above class, I'm pretty certain that you'll grasp easily the logic that stands behind the template pattern. As you can see, this abstract template class presents a method called "displayFormattedFileContents()," which obviously is its workhorse, since it establishes a formatting algorithm that will be applied to all data fetched from a specific file.
Also, it's valid to notice here the existence of two additional methods. These are used internally by the template class to implement the formatting algorithm. In this particular case, the first method, that is the one called "getFileSize()," logically is tasked with returning to calling code the size of the target file from which the data is retrieved, while the second one, named "getFormattedFileContents()," defines a generic interface for displaying file contents as (X)HTML, XML or an uppercased string. Quite simple, isn't it?
Well, at this time you already saw how the previous template class looks, so what's the next thing to do? As you saw, the "getFormattedFileContents()" method that you learned before doesn't have a concrete definition, which means that it must be implemented by the corresponding subclasses.
Therefore, the respective signatures of these child classes will be shown in the next section. Jump ahead and keep reading to find out how they will look.
Next: Building a few simple subclasses >>
More PHP Articles
More By Alejandro Gervasio