Besasam
Besasam

Reputation: 47

Doctrine 2 fatal error when adding new association

I have two object classes, Session and Speaker, with a many-to-many association. When I want to add a speaker to a session, I use this code:

109   $session->getSpeakers()->add($speaker);
110   $speaker->getSessions()->add($session);

This works fine for existing sessions. Now when I instantiate a new session and then try to add speakers the same way, I get this error:

Fatal error:  Uncaught Error: Call to a member function add() on null in C:\###\api\sessions\update.php:109
Stack trace:
#0 {main}
  thrown in C:\###\api\sessions\update.php on line 109

I presume this is because the new session doesn't have any speakers yet and thus returns null when I call getSpeakers().

However I can't find anything in the Doctrine Docs about how to circumvent this. Did I miss a step somewhere?

Upvotes: 0

Views: 34

Answers (1)

Mike Doe
Mike Doe

Reputation: 17576

Have you initialized your collection in the constructor?

// missing parts skipped for brevity
public function __construct(...)
{
    // ...
    $this->speakers = new ArrayCollection();
    $this->sessions = new ArrayCollection();
}

Anyway your code is poor quality in terms of SOLID. You should have methods called:

addSpeaker(Speaker $speaker)
addSession(Session $session)

so only the object itself knows how to handle the collection. For the time being you leak its internal details outside the class which is bad (SRP, law of Demeter violation), because it decreases code maintainability in time.

Upvotes: 2

Related Questions