danielrvt danielrvt - 3 months ago 16x
PHP Question

Doctrine collection is null upon object initialization [In some cases only]

This is my problem: I create an object, then I get a collection from that object. For some objects, in some controllers, this collections return an empty

Object, for some it returns just null.

Reading in SO, they say it is better to always initialize all
relationships in the entities constructor, is this really the case? Where is this documented?

This is an example of the problem:

$p = new Person();
$p->getRelatives(); // null, should be empty CollectionArray.

In the mean time, in another Controller Class...

$w = new Woman();
w->getMen(); // this returns an empty CollectionArray class -.-

Hope you guys can point me in the right direction, I really don't want to go through all my entities and create a constructor for them just because of this!

Besides, whats really annoying is this non deterministic behavior in which the collections are returned.


And that's the reason, why the documentation says, all collections should be initialized:

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class User
    /** @ManyToMany(targetEntity="Group") */
    private $groups;

    public function __construct()
        $this->groups = new ArrayCollection();

    public function getGroups()
        return $this->groups;

And the time, if a collection is null or not null, if not initialised is determenistic. Without initialisation the $groups field only contains an instance of Doctrine\Common\Collections\Collection if the user is retrieved from Doctrine, however not after you instantiated a fresh instance of the User. When your user entity is still new $groups will obviously be null.