My brain is starting to hurt so I decided I'd ask here.
I have a data object, Employee. Getters, setters, formatters, etc. I have a manager, EmployeeManager, which handles database access and other things. Right now I have a large validation block in EmployeeManager, but I've been wondering if I could move some of that to the setters.
For example, right now I have;
public function getSSN($bFormatted = true) {
return ($bFormatted) ? $this->format_ssn($this->SSN) : $this->SSN;
}
public function setSSN($s, $bValidate = false)
{
// If we're validating user entry, save a copy.
// Either way, store a trimmed version.
if ($bValidate): $this->SSNToValidate = $s; endif;
$this->SSN = str_replace('-', '', $s);
}
public function getSSNToValidate() { return $this->SSNToValidate; }
What this does is:
* When you set an SSN, if it's being done by the system (like from the database) then it does setSSN('123456789', false)
, because SSNs are stored in the database sans dashes.
* When you set an SSN from user input, it does simply setSSN('123-45-6789')
then not only trims the dashes, but also stores a raw version to validate (because I want to validate based on format)
* When you get an SSN, if formatting is requested (and it always is except when you're writing to the database), it formats it based on another function in the Employee class.
So my question is: Could I perhaps add the validation to the setter here, instead of relying on the monolithic validate function in the Manager class? Because I'm starting to have to deal with errors coming from all over the application, I've decided for the moment to move to a central Error Handler static class, rather than each manager maintain its own list of errors.
And because of this, I could easily add error handling to this:
public function setSSN($s, $bFromUser = false)
{
if ($bFromUser && !$this->validateSSN($s))
{
ErrorHandler::add(array('ssn' => 'Invalid SSN entered'));
}
else
{
$this->SSN = str_replace('-', '', $s);
}
}
So I guess my question is: Does this make sense at all or am I hosing myself by moving validation from the manager (to be performed on demand or just before writing to the database) to the object (to be performed on entry)?
This is overall generic, I'm just using SSN as a good example.