Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable collections in Doctrine 2?

I'm looking for a way to return an immutable collection from a domain object in Doctrine 2. Let's start with this example from the doc:

class User
{
    // ...

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

// ...
$user = new User();
$user->getGroups()->add($group);

From a DDD point of view, if User is the aggregate root, then we'd prefer:

$user = new User();
$user->addGroup($group);

But still, if we do need the getGroups() method as well, then we ideally don't want to return the internal reference to the collection, as this might allow someone to bypass the addGroup() method.

Is there a built-in way of returning an immutable collection instead, other than creating a custom, immutable collection proxy? Such as...

    public function getGroups()
    {
        return new ImmutableCollection($this->groups);
    }
like image 404
BenMorel Avatar asked Sep 10 '11 23:09

BenMorel


1 Answers

The simplest (and recommended) way to do it is toArray():

return $this->groups->toArray();
like image 167
BenMorel Avatar answered Sep 24 '22 19:09

BenMorel