Answer the question
In order to leave comments, you need to log in
Best practices for validating Entity properties in Symfony 2
In the process of studying Symfony 2, the question arose of how best to organize the validation of elements of Doctrine entities. For example, I have an entity User, it has an $email property and I want to be sure that this property is a valid email.
class User
{
/**
* @var string
* @ORM\Column(type="string")
*/
protected $email;
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
* @return $this
*/
public function setEmail($email)
{
// Вот здесь по-идее должен быть код проверки
$this->email = $email;
return $this;
}
}
@Assert\xxxx
annotations and validate from the outside, but at first glance the method does not look quite suitable, or is it just that?Answer the question
In order to leave comments, you need to log in
You should start with this tutorial: symfony.com/doc/current/book/validation.html The
comment above described another validation option. Everything here is for an amateur: I didn’t like the annotations and I write all the configs in yml, including the validator.
So far, it is impossible to answer your question more specifically, because there is no question. The manual contains all the cases that may be useful to you at the first stage, if you have questions - ask in this thread, I will try to answer
> However in Symfony I can't get DI container from entity
Yes. Validation is carried out externally. In service. Not within the entity.
Validation rules are set in Resources/config/validation.yml
However, it is quite logical to hide the methods for checking the properties of an object in the object itself and carry out the verification using the appropriate method. I like to use such a pattern for this,
there is a property, say referalUserId
The class object is correct, if we say this very referalUserId is contained / not contained in any table of some database - we do all the checks in the class method
public function isReferalUserIdLegal(){
// our validation code
return true/false depending on the results of the check
}
and in the validator.yml we point to the check class and method
# src/Acme/MyBundle/Resources/config/validation.yml
Acme\MyBundle\Entity\Myclass:
getters:
ReferralUserIdLegal:
- "True": { message: "Referral can only be very referral!" }
Voila
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question