php - Doctrine entity validation at construct -


i'm trying improve myself doctrine, , doing best practices. found presentation of best practices : https://ocramius.github.io/doctrine-best-practices/#/50

i try have valid object after __construct. (see https://ocramius.github.io/doctrine-best-practices/#/52) i'm using @assert annotation validating object.

how can validate ? have inject validator service inside object @ __construct ?

my object :

class person {     /**      * @var int      *      * @orm\column(name="id", type="guid")      * @orm\id      * @orm\generatedvalue(strategy="uuid")      * @expose      */     private $id;      /**      * @var int      *      * @orm\column(name="name", type="string")      * @assert\email()      */     private $email;      public function __construct($email, validatorinterface $validator){            $this->email = $email;           $validator->validate($this); // practice ?      } 

my final goal unit test input validation of entity.

thank you

edit :

basing on answer of yonel, added in end of constructor :

 $errors = $validator->validate($this);     if(count($errors) > 0) {         $errorsstring = (string) $errors;         throw new invalidargumentexception($errorsstring);     } 

is practices or not ? if not, why ? thank you!

the presentation take best practice both , world.

the principle highlighting presentation layer of application can use form component can validate user input data used instantiate entity.

in example of presentation named constructor take argument form, validation of email address done form (validating user input).

the meaning of having object valid state intended having object of type user have both name, surname ad email valid (as example not null).

so can have following object:

class user {      private $name;      private $surname;      private $email;      private function __construct(string $name, string $surname, string $email)     {         $this->name = $name;         $this->surname = $surname;         $this->email = $email;     }      public static function create(string $name, string $surname, string $email): user     {         return new static($name, $surname, $email);     }      public function fromformdata(forminterface $form):user     {         // form validate user input (i.e. valid email address)         return self::create($form->get('name'), $form->get('surname'), $form->get('email'));     }  } 

another approach using dto or can take @ this useful bundle validate dtos object.

hope help


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -