Home arrow PHP arrow Page 2 - PHP: Effects of Wrapping Code in Class Constructs

Converting the Helper - PHP

In this first part of a two-part tutorial, I use a somewhat contrived example to show why you should avoid coding static helper classes in PHP.

TABLE OF CONTENTS:
  1. PHP: Effects of Wrapping Code in Class Constructs
  2. Converting the Helper
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
December 28, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
{
    /**
     * Validate the given value
     */
    public function validate(); 
}     
     
As you can see above, the contract defined by this brand new interface is really simple. Its existence is a more efficient solution than the static class created previously, as it allows us to not only to apply the “Coding to an interface, not to an implementation” principle, but permits us to easily build different kinds of validators without breaking the functionality of existing client code.

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
{
    const DEFAULT_ERROR_MESAGE = 'The supplied value is invalid.';
    protected $_value;
    protected $_errorMessage = self::DEFAULT_ERROR_MESAGE;
   
    /**
     * Constructor
     */
    public function __construct($value = null, $errorMessage = null)
    {  
        if ($value !== null) {
            $this->setValue($value);
        }
        if ($errorMessage !== null) {
           $this->setErrorMessage($errorMessage);
        }
    }
   
    /**
     * Set the value to be validated
     */
    public function setValue($value)
    {
        $this->_value = $value;
    }
   
     /**
     * Get the inputted value
     */
    public function getValue()
    {
        return $this->_value;
    }
     
    /**
     * Set the error message
     */
    public function setErrorMessage($errorMessage)
    {
        if (!is_string($errorMessage) || empty($errorMessage)) {
            throw new \InvalidArgumentException('The error message is invalid. It must be a non-empty string.');
        }
        $this->_errorMessage = $errorMessage;
    }
   
    /**
     * Get the error message
     */
    public function getErrorMessage()
    {
        return $this->_errorMessage;
    }
   
    /**
     * Reset the error message to the default value
     */
    public function resetErrorMessage()
    {
        $this->_errorMessage = self::DEFAULT_ERROR_MESAGE;
    }       
}

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!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: