9

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 ?

1
  • 1
    Suppose a client that use your entity must check for null value instead of count for zero elements, and some other doctrine stuff and behaviour that i ignore....
    – Matteo
    Feb 10, 2015 at 14:09

1 Answer 1

6

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".

2
  • 1
    What do ou mean by "fail"? I tried $car = new Car(); $wheel = new Wheel(); $car->addWheel($wheel); var_dump($car->getWheels());, with both contructor empty. I don't see any kind of error, and the var_dump shows me the $wheelas expected.
    – Blacksad
    Feb 17, 2015 at 10:12
  • 2
    Update your question showing your Car entity, especially where you declare wheels and the addWheel/getWheels methods.
    – Cerad
    Feb 17, 2015 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.