HomePHP Page 2 - Processing File Data with Template Classes in PHP 5
Building a basic file processing class - PHP
If you're looking for a friendly guide on how to implement the template design pattern with PHP 5, then this group of articles might be what you need. Welcome to the final installment of the series that began with "Working with template classes in PHP 5." As the title indicates, this series steps you through creating template classes in PHP-controlled development environments, and also shows you how to use this rather uncommon pattern in real-world situations.
A good point to start demonstrating an approachable implementation of the template pattern consists of defining a basic file processing class, which will be used later on by a template object to display contents fetched from a specific target file.
As you'll see, the file contents will be displayed either in (X)HTML and XML format or as an uppercased string, depending on which template class will be used for this purpose. So far there's nothing unexpected, right?
Now that you know the reasons for using a template object, please pay attention to the signature of the file processing class. It looks like this:
// define 'FileProcessor' class class FileProcessor{ private $dataFile; private $data; public function __construct($dataFile='default_file.txt', $data='This is the default data.'){ if(!file_exists($dataFile)){ throw new Exception('A valid data file must be provided!'); } if(!is_string($data)){ throw new Exception('File data must be a string!'); } $this->dataFile=$dataFile; $this->data=$data; } // write data to target file public function writeData(){ if(!$fp=fopen($this->dataFile,'w')){ throw new Exception('Error opening data file!'); } if(!fwrite($fp,$this->data)){ throw new Exception('Error writing data to file!'); } flose($fp); } // read data from target file public function readData(){ if(!$contents=file_get_contents($this->dataFile)){ throw new Exception('Error reading from data file!'); } return $contents; } // get size of data file public function getFileSize(){ if(!$size=filesize($this->dataFile)){ throw new Exception('Error retrieving size of data file!'); } return $size; } }
As illustrated above, the logic followed by the previous "FileProcessor" class is indeed very easy to understand. In crude terms, all that this class does is read and write data to a specified target file, in addition to determining the size of this file by using its simple "getFileSize()" method.
However, as you might have guessed, the previous class isn't the main objective of this tutorial at all. As I said before, I'm going to use an instance of it, so it can be adequately processed by a template object. Sounds pretty simple, doesn't it?
Of course, as you know, the signature of this template class remains undefined, so if you want to see how the template in question will look, please click on the link below and keep reading.