I'm using this pattern for the first time and wanted to check if this is the correct implementation.
class.validator.strategy.php
abstract class ValidatorStrategy
{
abstract public function check( $name, $val );
}
class.text.validator.php
class TextValidator extends ValidatorStrategy
{
public function check( $name, $val )
{
//logic here
}
}
class.number.validator.php
class NumberValidator extends ValidatorStrategy
{
public function check( $name, $val )
{
//logic here
}
}
class.validator.php
include('validator.strategy.php');
include('class.text.validator.php');
include('class.number.validator.php');
include('class.email.validator.php');
class Validator
{
//holds strategy object
protected $validatorStrategy = array();
//holds form field
protected $fields = array();
public function __construct()
{
$this->validatorStrategy[ 'text' ] = new TextValidator();
$this->validatorStrategy[ 'number' ] = new NumberValidator();
$this->validatorStrategy[ 'email' ] = new EmailValidator();
}
public function ruleForTextField( $name, $value )
{
$this->fields[ $name ][ 'value' ] = $value;
$this->fields[ $name ][ 'type' ] = 'text';
}
public function ruleForNumbertField( $name, $value )
{
$this->fields[ $name ][ 'value' ] = $value;
$this->fields[ $name ][ 'type' ] = 'number';
}
public function ruleForEmailField( $name, $value )
{
$this->fields[ $name ][ 'value' ] = $value;
$this->fields[ $name ][ 'type' ] = 'email';
}
public function isValidate()
{
$status = 0;
foreach ( $this->fields as $key => $val )
{
if ( !$this->validatorStrategy[ $val[ 'type' ] ]->check( $key, $val ) )
{
$status++;
}
if ( $status == 0 )
{
return true;
}
else
{
return false;
}
}
}
Uses:
$validator = new Validator();
$validator->ruleForTextField('username', $_POST['username'] );
$validator->ruleForNumberField('age', $_POST['age'] );
$validator->ruleForEmailField('email', $_POST['email'] );
if($validator->isValidate())
{
echo 'validated';
}
else
{
echo 'fail validation';
}
Inside the isValidate()
method, it iterate against all validator strategy and perform appropriate logic.
Is this is the correct way to use this pattern?