正确的方法是在模式中使用验证器,然后使用validate()
代码中的方法进行检查。这是一个例子:
<database ...>
<table ...>
<!-- the "required" attribute here only sets the DB property -->
<column name="email" type="varchar" required="true" />
...
<!-- Adds the unique index in the DB (but nothing in PHP code!) -->
<unique>
<unique-column name="email" />
</Unique>
...
<validator column="email">
<!-- this validator rule makes the $obj->validate() method fail on null -->
<rule name="required" message="The email is required!" />
<!-- this validator rule makes the $obj->validate() method fail on empty string -->
<rule name="minLength" value="1" message="The email cannot be blank!" />
<!-- you could add a regular expression to only match email addresses here -->
<rule name="match" value="/regular expression/" message="Please enter a valid email address!" />
<!-- adds a validation that the field is unique before trying to update DB -->
<rule name="unique" message="That email address is not unique!" />
</validator>
</table>
</database>
然后在您的preSave()
代码中,您可以执行以下操作:
class User extends BaseUser {
...
public function preSave(PropelPDO $con = null) {
// does the object pass all validations?
if (!$this->validate()) {
$errors = array();
// something failed, go through each failure and capture message:
foreach ($this->getValidationFailures() as $failure) {
$errors[] = $failure->getMessage();
}
// throwing an Exception will stop the save() from occurring
throw new InvalidArgumentException(implode("||", $errors));
}
return true; // if you get here, go ahead and save
}
}
在您的脚本中,您会这样调用save()
:
...
$user = new User();
try {
// try to save (could fail)
$user->save();
} catch (InvalidArgumentException $e) {
// we have errors, split the exception message to get each one separately
$errorMessages = preg_split(/\|\|/, $e->getMessage());
// handle the messages however you need to
}
在 Propel 文档中阅读有关验证器的更多信息。