教义2中的不可变集合? [英] Immutable collections in Doctrine 2?

查看:75
本文介绍了教义2中的不可变集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从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);

DDD 的角度来看,如果User是聚合根,则我们希望:

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

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

但是仍然,如果我们确实还需要getGroups()方法,那么理想情况下我们不希望返回对集合的内部引用,因为这可能使某些人可以绕过addGroup()方法.

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

推荐答案

最简单(推荐)的方法是

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

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

这篇关于教义2中的不可变集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆