I’m trying to find the best way to organize a validator class, hopefully using OOP best practices.
I thought a good might be to have a general validator class that I extend as the need arises. However, I am unsure of a good way to implement a validateAll method. I am not sure how to “reach” back into a parent class and get its validator methods in a way that wont cause me to have to constantly sync up the parent and child class and is programmatically succinct and extensible (I will want more methods in the child class eventually). Here is some sample code of the problem:
class GeneralValidator
{
protected $name = null;
protected $password = null;
protected $errors = array();
public function setName($name)
{
$this->name = $name;
}
public function validateName()
{
// stuff here to validate name, return true if okay, false if it fails validation or is null, and set a message in the errors array
}
public function setPassword($password)
{
$this->password = $password;
}
public function validatePassword()
{
// stuff here to validate password, return true if okay, return false if it fails validation or is null, and set a message in the errors array
}
public function validateAll()
{
if ($this->validateName($this->name) AND $this->validatePassword($this->password))
{
return true;
}
return false;
}
}
class SpecificValidator extends GeneralValidator
{
protected $email = null;
public function setEmail($email)
{
$this->email = $email;
}
public function validateEmail()
{
// stuff here to validate password, return true if okay, return false if it fails validation or is null, and set a message in the error message array
}
public function validateAll()
{
// how to implement this one?
}
}
But what if I want a “validateAll” method for SpecificValidator but I also want it to use all all validation methods in the child class as well? I understand it is good practice to make a common interface across related objects, so that all Validators can use a method like >validateAll(). Should I just hard code all the validation routines into SpecificValidator, or is there a better way?