Doctrine 2中不可变的集合?

Ben*_*min 5 collections orm doctrine domain-driven-design doctrine-orm

我正在寻找一种从Doctrine 2中的域对象返回不可变集合的方法.让我们从doc中的这个例子开始:

class User
{
    // ...

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

// ...
$user = new User();
$user->getGroups()->add($group);
Run Code Online (Sandbox Code Playgroud)

DDD的角度来看,如果User是聚合根,那么我们更喜欢:

$user = new User();
$user->addGroup($group);
Run Code Online (Sandbox Code Playgroud)

但是,如果我们确实需要该getGroups()方法,那么理想情况下我们不希望将内部引用返回到集合,因为这可能允许某人绕过该addGroup()方法.

除了创建自定义的,不可变的集合代理之外,是否存在返回不可变集合的内置方法?如...

    public function getGroups()
    {
        return new ImmutableCollection($this->groups);
    }
Run Code Online (Sandbox Code Playgroud)

Ben*_*min 5

最简单(和推荐)的方法是toArray():

return $this->groups->toArray();
Run Code Online (Sandbox Code Playgroud)