As usual, the most effective way to shed some light on this process is by means of some concrete code samples. So take a look at the one below, which defines the aforementioned interface: (Library/Helper/ValidatorInterface.php) <?php namespace Library\Helper; interface ValidatorInterface With this interface already declared, the next step toward the creation of separate, instantiable validators is to encapsulate their common functionality in an abstract class. Not surprisingly, I called this one “AbstractValidator” and its definition is as follows: (Library/Helper/AbstractValidator.php) <?php namespace Library\Helper; abstract class AbstractValidator The source code of the above abstract parent speaks for itself. This base class simply implements a couple of basic mutators along with a getter (aside from the constructor), which allow us to assign and retrieve the error message associated with a particular validator. It's nothing especially complex, in reality. With the previous class up and running already, it’s time to recap and see what’s been achieved so far. One the one hand, there exists a segregated interface, which makes spawning new validators a breeze. On the other hand, the earlier class is nothing but a simple container, which hides functionality shared by the validators in question (except for the validation process itself, of course). If you’re like me, you're probably wondering how to build up a set of concrete, more granular validators to replace the previous “does-all” static helper. Well, the process would be as easy as subclassing the abstract parent and implementing the “ValidatorInterface” interface. But I’m getting ahead of myself, since the full details of this process will be covered in depth in the next installment. Closing Remarks In this first part of a two-part tutorial, I used a fairly contrived example to demonstrate why you should avoid coding static helper classes in PHP, regardless of whether you’re building an object-oriented framework, a custom library or your next killer application. Even if you’re not a strong worshipper of the SOLID principles, the side effects generated by this kind of helper are numerous and detrimental. In the name of plain common sense and good programming habits, try to stay away from them simply by making them non-static. If you want to see how I plan to fix my own static validator, and turn it into a set of polymorph instances which can be injected, unit-tested and passed around, don’t miss the final part!
blog comments powered by Disqus |
|
|
|
|
|
|
|