Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of initializing collections in the constructor

I'm using Doctrine with Symfony and the entity generator initializes collection in the entity's constructor. For example:

/**
 * @var MyProject\MyBundle\Entity\Foo
 * 
 * @ORM\ManyToMany(targetEntity="MyProject\MyBundle\Entity\Foo")
 */
private $foos;

public function __construct() {
    $this->foos = new \Doctrine\Common\Collections\ArrayCollection();
}

And I can read in Doctrine's best practices that... it is a good practice to do so.

But the question is: what is the interest?

I don't see any change if I remove this line in the constructor. I guess it is lazy-loaded then, but is the performance drop significant enough to take the time to write the constuctor (the app/console doctrine:generate:entities command doesn't feed the constructor with new ArrayCollection if the constructor already exist, so I have to do it manually).

And if it is really better to do it, should I do it for all relation or only the nullable=false one?

Imagine the entity Car in OneToMany with Wheel (not nullable) and OneToMany with Passenger (nullable). Should I initialyze only $wheels or both? And why ?

like image 614
Blacksad Avatar asked Feb 10 '15 13:02

Blacksad


1 Answers

Doctrine entities are just plain objects. When you load an entity from the database, Doctrine never calls the constructor and takes care of setting up your collections. Not really lazy loading but Doctrine will make sure the collections are created. That is why you have not noticed a difference.

However, if you use "new Entity() " to create a new instance then the constructor is needed to initialize your collections. If your collections are not initialized then your add methods will fail. Not too mention your get methods.

Always initialize all your collections regardless of the relation. Once again, if your don't then any attempt to access them will fail.

It's not "best practices" it's "required practices".

like image 135
Cerad Avatar answered Nov 01 '22 04:11

Cerad