Validation Wall

by atillaordog

I re-imagined data validation in PHP. Why did I do this? I found that current validation techniques are too strict and cannot be used alone.

So, I thought the following: validation is like a filter. A wall that has different doors, each door specific to a set of data. Data comes and in order to reach its destination, it has to go over the door. Now the door has rule-sets, these are the rules specific to a part from the data.

These rule sets are built from rules, that are the basic rules found in any validation system.

A wall can be built easily by simply grouping the rules to fit our needs.

Here is an example:

$title_ruleset = new MainRuleset('title', array( new NotEmpty() ));
$description_ruleset = new MainRuleset('description', array( new NotEmpty() ));
$categories_ruleset = new MainRuleset('categories', array( new NotEmpty() ));

$door = new Door(array($title_ruleset, $description_ruleset, $categories_ruleset));

$vw = new ValidationWall($door);

$post_passes = $vw->pass($post);

In this example we use the NotEmpty rule to check the title, the description and the category.

 

To use ValidationWall, you have to include the autoload file like:

include_once route/to/ValidationWall/folder/autoload.php';

Also you have to use the namespaces like:

use ValidationWallDoorMainDoor as Door;
use ValidationWallRuleSetMainRuleset as MainRuleset;
use ValidationWallRuleNotEmpty as NotEmpty;
use ValidationWallRuleNumeric as RuleNumeric;

After you initialized ValidationWall, you can start building your wall to fit your needs.

Main benefits:

  • It is totally stand-alone, usable anywhere in any script
  • Logically more understandable than general validation
  • Rules are custom, meaning you can build any rule you want, you just have to implement the interface or extends the abstract class
  • Build validation like you are playing Lego

You can find this little code here:

https://github.com/atillaordog/ValidationWall

Advertisement