As discussed in the previous section, one of the easiest ways to extend the functionality of a given class without having to use inheritance is simply by defining an adapter class. The adapter class will modify one or more methods of the original one to conform a specific model. This being said, and based upon all the prior sample classes, here is the complete process for creating the aforementioned adapter class. Take a look, please:
As you can see, the above defined “DirectoryProcessorAdapter” class is now capable of extending the functionality of the previous “DirectoryProcessor” by simply injecting this object into the corresponding constructor, and finally defining the completely new “fetchDetailedDirContent()” method. Here, it’s clear to see that this method combines the capacity of “fetchDirContent()” and “getDirInfo()” in one single block and displays the respective information on the browser. See how an adapter class now fits into the whole picture? Now that you hopefully grasped the logic that drives the “DirectoryProcessorAdapter” class that you learned before, I’d like to go one step forward and show you how to properly use this class. Therefore, examine the example listed below, which demonstrates a simple implementation of the adapter class:
As you’ll realize, the previous example demonstrates how easy it is to use the adapter class that I defined a few lines above. After a new directory processor object and its respective adapter have been instantiated, the “getDetailedDirInfo()” method is called up at the end of the script, which neatly displays the directory information detailed above. After all, implementing the adapter pattern with PHP 5 isn’t difficult. As you saw in the previous example, a given class can be easily modified without using inheritance, in cases where this approach is not viable. To wrap up We’ve come to the end of this first article. Hopefully, after learning all the concepts and examples given here, you’ll have a clearer idea of how to create an adapter class with PHP. But this educational journey hasn’t ended yet, since in the second (and last) tutorial you’ll learn how to create an adapter that works in tandem with the standard “DirectoryIterator” class, included with PHP 5, in addition to building adapters for MySQL. Therefore, meet you in the last part!
blog comments powered by Disqus |