I'm fairly new to object oriented programming here and am trying to get my head around the best way to go about creating Users and Validating them in the system.
My first attempt is below and my main questions apart from does it all seem correct is in regards passing a validator class to the save function and pros/cons to this.
A lot of the functionality has been stripped back to enable you to read it a bit easier, including removing any getters and setters but please assume they are there:
User Model
class User implements Validateable {
protected $name;
protected $email;
protected $validator;
// getters and setters for name, email, validator here
public function save( Validator $validator ) {
$this->validator = $validator;
if( $this->validator->validate( $this ) )
return true;
return false;
}
public function getRules() {
return [
'name' => new NameValidator( $this->name ),
'email' => new EmailValidator( $this->email )
];
}
}
Abstract Validator
abstract class ValidatorAbstract {
protected $errors;
public function getErrors() {
return $this->errors;
}
}
Name Validator
class NameValidator extends ValidatorAbstract {
protected $name;
protected $errors;
public function __construct( $name ) {
$this->name = $name;
}
public function validate() {
if( empty( $this->name ) )
$this->errors[] = 'Invalid Name';
if( $this->errors )
return false;
return true;
}
}
Email Validator
class EmailValidator extends ValidatorAbstract {
protected $email;
protected $errors;
public function __construct( $email ) {
$this->email = $email;
}
public function validate() {
if( !filter_var( $this->email, FILTER_VALIDATE_EMAIL ) ) :
$this->errors[] = 'Invalid Email';
endif;
if( $this->errors )
return false;
return true;
}
}
User Validator
class UserValidater implements Validator {
protected $data;
protected $rules;
protected $errors;
public function validate( Validateable $obj ) {
$this->rules = $obj->getRules();
foreach( $this->rules as $rule ) :
if( !$rule->validate() )
$this->errors[] = $rule->getErrors();
endforeach;
if( $this->errors )
return false;
return true;
}
public function getErrors() {
return $this->errors;
}
}
Validator Interface
interface Validator {
public function validate( Validateable $data );
public function getErrors();
}
Validateable Interface
interface Validateable {
public function getRules();
}
And finally some example code using all of the above:
$user = new User;
$user->setName( 'Peter' );
$user->setEmail( '[email protected]' );
if( $user->save( new UserValidater ) ) :
// do some stuff
else :
$errors = $user->getValidator()->getErrors();
// do some stuff with the errors
endif;