I build a collection to ensure only valid entities in an array so I don't have to validate after every function / method call as I could rely on the collection to have only valid entities stored.
class WorldCollection implements Collection, ArrayAccess {
private $container = array();
private $oValidator;
public function __construct (Validator $oWorldValidator) {
$this->oValidator = $oWorldValidator;
}
public function offsetExists ($offset) {
return isset($this->container[$offset]);
}
public function offsetGet ($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* READ ME
*/
public function offsetSet ($offset, $value) {
$this->oValidator->validate($value)
if (is_null ($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetUnset ($offset) {
unset($this->container[$offset]);
}
}
As I want to separate concerns and follow dependency injection I inject the Validator
in the constructor of the collection and validate in the ofsetSet
method to ensure only valid values will be stored.
class WorldValidator implements Validator {
public function validate($aWorld) {
if (!is_array($aWorld)) {
throw new WorldValidationException('invalid type', WorldValidationException::ERROR_CODE_INVALID_TYPE);
}
return true;
}
}
(The validator is simplified for example purpose.)
- Did I seperate it right? Or should I handle this kind of validation differently?
- Should I catch the validation exception to not disturb the program
flow? If so should I store the exception and offer a
getErrors
method? - Should I rename the collection
ValidWorldCollection
and extend fromWorldCollection
? - Should the
InvalidWorldException
extendRuntimeException
orLogicException
? Same forWorldValidationException
in the validator - Should I create a World Class and exclude the
Validation
from theCollection
usinginstanceof
? - Should I have used a more appropriate Spl DataStructure? (SplObjectStorage?) Or is it all a waste of time?