Validator refactored to be OO Based on my previous post I completely re-factored my code to make it object oriented.

Anything I could improve when it comes to:


Object oriented code;
Efficiency;
Readability.


Any other suggestions are also welcome!

Validator class:

class Validator
{
    private $rules  = [];
    private $errors = [];

    public function getErrors($rulename = null)
    {
        if ($rulename) {
            return isset($this-&gt;errors[$rulename]) ? $this-&gt;errors[$rulename] : null;
        }

        return $this-&gt;errors;
    }

    # rules will be checked against in same order as specified
    public function setRule($name, Array $rules)
    {
        if (!array_key_exists($name, $this-&gt;rules)) {
            foreach ($rules as $rule) {
                if (!$rule instanceof IRule) {
                    throw new Exception('Array must only contain instances of IRule.');
                }
            }

            $this-&gt;rules[$name] = $rules;
        } else {
            throw new Exception(sprintf('Rule %s already exists.', $name));
        }
    }

    public function validate($rulename, $input)
    {
        foreach ($this-&gt;rules[$rulename] as $rule) {
            try {
                $rule-&gt;check($input);
            } catch (Exception $e) {
                $this-&gt;errors[$rulename][] = $e-&gt;getMessage();
            }
        }

        if (isset($this-&gt;errors[$rulename])) {
            return false;
        }

        return true;
    }
}


One of the rule classes:

class Between implements IRule
{
    private $errMsg = 'Must be between %s and %s.';

    private $inclusive;
    private $max;
    private $min;

    public function __construct($min, $max, $inclusive = true, $errMsg = null)
    {
        $this-&gt;min       = $min;
        $this-&gt;max       = $max;
        $this-&gt;inclusive = $inclusive;

        if ($errMsg !== null) {
            $this-&gt;errMsg = $errMsg;
        }
    }

    public function check($input)
    {
        if ($this-&gt;inclusive &amp;&amp; $input &gt;= $this-&gt;min &amp;&amp; $input &lt;= $this-&gt;max) {
            return true;
        } elseif (!$this-&gt;inclusive &amp;&amp; $input &gt; $this-&gt;min &amp;&amp; $input &lt; $this-&gt;max) {
            return true;
        } else {
             throw new Exception(sprintf($this-&gt;errMsg, $this-&gt;min, $this-&gt;max));
        }
    }
}


Example:

$validator = new Validator();

$validator-&gt;setRule('name',  [new NotEmpty(), new MaxChars(20), new Alpha(true)]);
$validator-&gt;setRule('email', [new NotEmpty(), new Email()]);

$validator-&gt;setRule('age',
    array(
        # last constructor argument overrides default error message
        new NotEmpty('You did not enter your age.'),
        new Numeric('Your age can only be numerical.'),
        new Between(13, 17, true, 'Only teenagers are allowed.')
    )
);

$validator-&gt;validate('name',  'John');
$validator-&gt;validate('email', 'Doe');
$validator-&gt;validate('age',   'Hello');

# report
if (!$validator-&gt;getErrors()) {
    echo '&lt;b&gt;Input(s) valid:&lt;/b&gt; Passed complete validation.';
} else {
    echo '&lt;b&gt;Input(s) invalid:&lt;/b&gt; Failed complete validation.';
}
This is a really solid start. I only have a couple of suggestions.


Instead of defining the rules outside of the Validator class, it might be a good idea to sub class Validator and set the rules inside the constructor.
Create public methods specifically for each kind of validator.


Some pseudo code to get the main idea:

validator.php

class Validator
{
    private $rule_collection = array();

    public function __construct()
    {
    }

    public function ruleFor($property)
    {
        if (!isset($this-&gt;rule_collection[$property]))
            $this-&gt;rule_collection[$property] = new RuleBuilder($property);

        return $this-&gt;rule_collection[$property];
    }

    public function validate($model)
    {
        $valid = true;

        foreach ($this-&gt;rule_collection as $property =&gt; $rule_builder)
        {
            foreach ($rule_builder-&gt;rules as $rule)
            {
                if (!$rule-&gt;validate($model-&gt;$property))
                    $valid = false;
            }
        }

        return $valid;
    }
}


rule_builder.php

interface IRule
{
    public validate($value);
    public get_message();
}

class RuleBuilder
{
    private $property;
    public $rules = array();

    public function __construct($property)
    {
        $this-&gt;property = $property;
    }

    public function isRequired()
    {
        return $this-&gt;addRule(new RequiredRule());
    }

    public function length($min, $max = -1)
    {
        return $this-&gt;addRule(new LengthRule($min, $max));
    }

    public function addRule(IRule $rule)
    {
        $this-&gt;rules[] = $rule;
        return $this;
    }
}


And your specific validator:

class UserValidator extends Validator
{
    public function __construct()
    {
        $this-&gt;ruleFor('name')
            -&gt;isRequired()
            -&gt;length(20);
    }
}


To use it:

$user = new User();
$user-&gt;name = "Foo";
$validator = new UserValidator();

if ($validator-&gt;validate($user))
    // save
else
    // redraw form and show errors


This way all of your rule classes are hidden. All of the validation rules are portable because they are created inside a model specific class, and it's easy to use an IDE's auto complete feature to discover which rules are available since the RuleBuilder class has strongly typed methods encapsulating each rule.

On top of that, the IRule interface just accepts a value and not a model, making each rule unit testable to ensure your validation library is functioning properly.

And for those who do some .NET/C# development, this pattern probably looks familiar if you've used the FluentValidation NuGet package for Visual Studio. Say what you want about .NET development, but there are some gems out there. I do like the pattern that FluentValidation uses.