Doctrine 2 validation
I have a proble开发者_高级运维m with validation. In Doctrine 1 i used this:
if ($model->isValid()) {
$model->save();
} else {
$errorStack = $model->getErrorStack();
...
}
and in $errorStack i got the column name and the error message. But in Doctrine 2 I can use just it:
Entity
/**
* @PrePersist @PreUpdate
*/
public function validate()
{
if ($this->name == null)) {
throw new \Exception("Name can't be null");
}
}
Controller:
try {
$user = new \User();
//$user->setName('name');
$user->setCity('London');
$this->_entityManager->persist($user);
$this->_entityManager->flush();
} catch(Exception $e) {
error_log($e->getMessage());
}
but I have two problems whit it:
- i don't know which column?
- i don't want to check unique manually
If i skip validate() from entity the unique will be catched (from this error.log)
Unique violation: 7 ERROR: duplicate key value violates unique constraint "person_email_uniq"
but for example the user save 2 records and the first is wrong, but the second valid, after the first save the EntityManager will close and I can't save the second(good) record because of "The EntityManager is closed".
Which is the best solution for this problem?
There are few ways to do validation in D2: - business logic related to one entity as you described in your post - validation based on listeners, check http://www.doctrine-project.org/docs/orm/2.0/en/reference/events.html#preupdate, ValidCreditCardListener example - validation based on third party libraries, something similar described here: Zend_Validate_Db_RecordExists with Doctrine 2? and Zend_Validate: Db_NoRecordExists with Doctrine If you use a particular framework for form rendering you can integrate validation into it.
I used validation in entities for business logic related to one entity:
/**
* @PrePersist @PreUpdate
*/
public function validate()
{
$this->errors = array();
if ($this->name == null)) {
$this->errors['name'][] = 'Something wrong';
}
if (0 < count($errors)) {
throw new Exception('There are errors');
}
}
public function getErrors()
{
return $this->errors;
}
and listeners validation to force some rules such as uniqueness because in my application entities can be created not only based on forms.
Remember to define @HasLifecycleCallbacks in the entity.
/**
* @Entity @Table(name="songs") @HasLifecycleCallbacks
*/
class Song
{
...
/** @PrePersist @PreUpdate */
public function doStuffOnPreUpdatePrePersists()
{
...
}
}
精彩评论