Immutable collections in Doctrine 2?

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

class User { // ... public function getGroups() { return $this->groups; } } // ... $user = new User(); $user->getGroups()->add($group); 

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

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

But still, if we also need the getGroups() method, then ideally we do not want to return an internal reference to the collection, as this may allow someone to bypass the addGroup() method.

Is there a built-in way to return an immutable collection instead of creating a custom immutable immutable proxy? Such as...

  public function getGroups() { return new ImmutableCollection($this->groups); } 
+4
source share
2 answers

The easiest (and recommended) way to do this is: toArray () :

 return $this->groups->toArray(); 
+5
source

I think the easiest way to achieve this is to use iterator_to_array .

iterator_to_array converts the iterable objects to arrays, so instead of returning the collection directly, you just do return iterator_to_array($this->foo); .

This has the added bonus of allowing you to use functions like array_map in returned lists, since they do not work with objects like arrays.

0
source

All Articles