【发布时间】:2011-05-26 19:11:57
【问题描述】:
不久前我问了一个类似的问题:Using the Data Mapper Pattern, Should the Entities (Domain Objects) know about the Mapper? 但是,它是通用的,我真的很感兴趣如何专门用 Doctrine2 完成一些事情。
这是一个简单的示例模型:每个Thing 可以从User 中获得一个Vote,一个User 可以转换多个Vote,但只有最后一个Vote 计数。由于其他数据(Msssage等)与Vote相关,所以在放置第二个Vote时,原来的Vote不能随便更新,需要更换。
目前Thing有这个功能:
public function addVote($vote)
{
$vote->entity = $this;
}
Vote 负责建立关系:
public function setThing(Model_Thing $thing)
{
$this->thing = $thing;
$thing->votes[] = $this;
}
在我看来,确保 User 只计算最后一个 Vote 是 Thing 和 not some service layer 应该确保的。
为了将其保留在模型中,新的Thing 函数:
public function addVote($vote)
{
foreach($this->votes as $v){
if($v->user === $vote->user){
//remove vote
}
}
$vote->entity = $this;
}
那么如何从域模型中删除Vote?我应该放松Vote::setThing() 以接受NULL 吗?我是否应该涉及Thing 可以用来删除投票的某种服务层?一旦票数开始累积,foreach 将会变慢 - 是否应该使用服务层来允许 Thing 搜索 Vote 而无需加载整个集合?
我肯定倾向于使用轻量级服务层;但是,有没有更好的方法来使用 Doctrine2 处理这类事情,或者我是否朝着正确的方向前进?
【问题讨论】:
标签: datamapper doctrine-orm service-layer