In the previous section, I demonstrated how to build an array iterator class that, thanks to the implementation of a protected constructor, can't be directly instantiated. Given that restriction, the next step that I'm going to take will consist of deriving a subclass from the iterator. The subclass will declare a pretty refined constructor method for traversing simple text files. Please take a close look at the definition of this new file iterator class, which is as follows: class FileIterator extends DataIterator { private $_file = 'data.txt';
// override parent constructor public function __construct($file = '') { if ($file !== '') { if (!file_exists($file)) { throw new Exception('Target file must be an existing file.'); } $this->_file = $file; } $data = file($this->_file); parent::__construct($data); } } As depicted above, the logic that drives the "FileIterator" class is extremely easy to follow. It simply overrides its parent's constructor to take as an input argument the text file that must be iterated over. The remaining methods are simply inherited from the base "DataIterator," so I'm not going to get back to them again, since they were already discussed in the previous section. So far, everything looks pretty good, right? At this point, there's a class that allows you to traverse text files in a painless fashion, thanks to the inherited functionality of a base class which implements a protected constructor. At the risk of being repetitive, I'd like to stress that a better result could be produced by declaring the corresponding parent abstract, but for now the parent iterator will live as a concrete class. Having explained how the file iterator does its thing, it's time to give it a try so you can see it in action. Therefore, in the last section of this tutorial I'm going to set up an example for you, which will demonstrate how to iterate easily over the contents of a sample text file. To see how this particular example will be developed, click on the link below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|