教义 2 中的不可变集合?
我正在寻找一种从 Doctrine 2 中的域对象返回不可变集合的方法。让我们从 doc:
class User
{
// ...
public function getGroups()
{
return $this->groups;
}
}
// ...
$user = new User();
$user->getGroups()->add($group);
来自 DDD 点的观点,如果 User
是聚合根,那么我们更愿意:
$user = new User();
$user->addGroup($group);
但是,如果我们确实还需要 getGroups()
方法,那么我们理想情况下不希望返回对集合的内部引用,因为这可能允许某人绕过 addGroup()
方法。
除了创建自定义的不可变集合代理之外,是否有一种内置方法可以返回不可变集合?例如...
public function getGroups()
{
return new ImmutableCollection($this->groups);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单(也是推荐)的方法是 toArray():
The simplest (and recommended) way to do it is toArray():
我想实现这一点的最简单方法是使用
iterator_to_array
。iterator_to_array
将可迭代对象转换为数组,因此您只需执行return iterator_to_array($this->foo);
即可,而不是直接返回集合。这样做的额外好处是可以在返回的列表上使用诸如 array_map 之类的函数,因为它们不适用于类似数组的对象。
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 doreturn 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.