As one might expect, putting the earlier validators in action is an extremely simple process, reduced to creating a few instances of them and calling …yes, their “validate()” method. To demonstrate how to accomplish this, below I wrote a basic script which uses the pertinent validators to check some sample input data (to keep things shorter and clearer, I haven’t implemented an autoloader, but you can do that if you want to). Here’s the script: <?php require_once __DIR__ . '/Helper/ValidatorInterface.php'; use Library\Helper\UrlValidator as UrlValidator, // create instances of the validators // validate a URL // validate an email address // validate a float number // validate an integer number /* displays the following The supplied value is an invalid integer number. */ While this brand new example is somewhat trivial, it shows how easy it is to utilize the functionality of the previous validators to determine the validity of some incoming data. In this case, client code consumes instances of them directly to perform the process of checking. It’s possible, though, to inject them into other objects (a composite implementation would be a typical situation), or something like that. Of course, the most relevant detail to notice here is that now we’re working with actual objects, and not simply with procedural code encapsulated within a bunch of static methods. This change itself makes it really worth all the work required to create the originating validator classes and the interface that they implement. To sum up: even in the simplest use cases (like the one shown above), be sure to build non-static classes. In doing so, you’ll be able to enjoy all of the goodies provided by object-oriented programming, which will translate into more robust and reliable code. Final Thoughts Over the course of this two-part tutorial, I showed from a practical standpoint why the use of static helper classes (in this case, a trivial “catch-all” validator) can be detrimental to building robust and scalable object-oriented applications in PHP (you should remember that the concept is language agnostic). In addition, I implemented a set of instantiable, fine-grained validators, which can be easily tested in isolation, injected into the internals of other objects, and so forth. Even though all of these examples were rather contrived, they made my point about the drawbacks of using purely static classes. In light of this, the next time you get your hands dirty writing your own helpers (or any other class, of course), bear in mind that you’re making your best programs by doing good object-oriented design, which is not class-based. The difference is subtle, but important. See you in the next PHP development tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|