coen-hyde / Shanty-Mongo

Shanty Mongo is a mongodb library for the Zend Framework. Its intention is to make working with mongodb documents as natural and as simple as possible. In particular allowing embedded documents to also have custom document classes.
Other
200 stars 52 forks source link

Checking requirements in the constructor #64

Closed ghost closed 12 years ago

ghost commented 12 years ago

In Document.php's __construct():

// Initialize input data
if ($this->isNewDocument() && is_array($data)) {
    foreach ($data as $key => $value) {
        $this->getProperty($key);
    }
}

What is the purpose of $this->getProperty($key)? Shouldn't it be $this->setProperty($key, $value)? That would allow us to validate already in the constructor and do stuff like:

try {
    $post = new Post($_POST);
} catch (Exception $e) {
    // react to bad input
}

Or am I missing something? :)

ghost commented 12 years ago

This would also require that Shanty_Mongo_Exception know which field triggered the validation error, something like:

class Shanty_Mongo_Exception extends Exception
{
    function __construct( $message, $field = null )
{
    $this->message = $message;
    $this->field = $field;
}

function getField()
{
    return $this->field;
}

}

And then in Mongo/Document.php setProperty, we can:

// Throw exception if value is not valid
if (!is_null($value) && !$validators->isValid($value)) {
    require_once 'Shanty/Mongo/Exception.php';
    throw new Shanty_Mongo_Exception(implode($validators->getMessages(), "\n"), $property);
}

... also tell the exception which property was the culprit.