PHP Page 2 - User-defined Interfaces in PHP 5: Turning MySQL Classes into Interface Implementers |
In order to work with different interface implementers, what I shall do is define two simple classes: a MySQL wrapping class and result-processing class, both aimed at working with MySQL data. Next, I’ll make the second class an implementer of the “HTMLRenderer” interface, so it’ll be capable of delivering HTML-formatted result sets through the specific definition of the “toHTML()” method. Now, objects of different types will be using the same interface. Let’s start by showing the “HTMLRenderer” interface, and then list the code for the “MySQL” wrapping class. Here are the definitions for both programming structures: // interface HTMLRenderer // class MySQL Essentially, the above class is the same one that I presented in some of my previous articles, with minor modifications, thus I won’t stick you with boring details explaining its functionality. The only point worth mentioning is the definition of the “query()” method. As explained in my article “Object Interaction in PHP: Introduction to composition”, this method returns a new “Result” object, which is useful for separating the logic for handling tasks related to connecting to the server, selecting a database and running queries from the code for processing result sets. It’s precisely the class that returns result-type objects which will be turned into an “HTMLRenderer” interface implementer, causing these objects to define a “toHTML()” method for obtaining formatted result sets. Having taken a quick look at the “MySQL” class, let’s see how the pertinent interface is implemented by result-type objects.
blog comments powered by Disqus |