Immutable collections in Doctrine 2?

北城余情 提交于 2019-12-22 06:03:17

问题


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);
    }

回答1:


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

return $this->groups->toArray();



回答2:


I suppose the easiest way to achieve that would be to use iterator_to_array.

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

This has the added bonus of making it possible to use functions like array_map on the returned lists, since they don't work on array-like objects.



来源:https://stackoverflow.com/questions/7375334/immutable-collections-in-doctrine-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!