I'm learning doctrine2, and having a problem how to call constructor automatically. For example, in my entity I have
/**
* @Entity
*/
class User{
....
public function __construct() {
exit('in');
}
}
and when I get the object this way:
$userObj = $em->find('User', 1);
I do get that object from database, but constructor is never called. I want to put some common things in constructor, like validation rules, or even to put sample code from the doctrine documentation like
$this->comments = new ArrayCollection();
This ofcourse works when I create new object in code for creating a user like
$user = new User(); //now constructor works just fine
Now, what is the "proper" way of getting the entity? I doubt I have to call constructor manually each time I user $em->find() with $user0bj->__construct(); ? This would kinda sucks then... Or I should use something other then ->find() to get single entity properly? I know I can user @PrePersist, and I am using it to actually do validation checks etc. I guess that I'm probably missing something here, or I'm trying to use constructor in a poor way. Thanks for any explanations and guides!
Why would you want to call the constuctor of already persisted entity? When you need to validate it you should have done the validation or initializations before you have persisted it. So When you call a already persisted entity there is no point to validate it. The right place to put validation and other initializations is the constructor method of entity. Eg.
/**
* @Entity
*/
class User{
protected $name;
public function __construct($name) {
if (isset($name)) {
//** validate the name here */
$this->name=$name;
} else {
throw new Exception("no user name set!");
}
}
}
According to the doctrine2 documentation Doctrine2 never calls __construct() method of entities. http://www.doctrine-project.org/docs/orm/2.0/en/reference/architecture.html?highlight=construct
I'm pretty certain that find
or similar isn't expected to call the constructor...
You need to hook into the @PostLoad event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With