【发布时间】:2010-04-23 09:34:01
【问题描述】:
我了解依赖注入的重要性及其在单元测试中的作用,这就是为什么下面的问题让我停下来的原因:
我努力不使用单例的一个领域是身份映射/工作单元模式(它密切关注域对象状态)。
//Not actual code, but it should demonstrate the point
class Monitor{//singleton construction omitted for brevity
static $members = array();//keeps record of all objects
static $dirty = array();//keeps record of all modified objects
static $clean = array();//keeps record of all clean objects
}
class Mapper{//queries database, maps values to object fields
public function find($id){
if(isset(Monitor::members[$id]){
return Monitor::members[$id];
}
$values = $this->selectStmt($id);
//field mapping process omitted for brevity
$Object = new Object($values);
Monitor::new[$id]=$Object
return $Object;
}
$User = $UserMapper->find(1);//domain object is registered in Id Map
$User->changePropertyX();//object is marked "dirty" in UoW
// at this point, I can save by passing the Domain Object back to the Mapper
$UserMapper->save($User);//object is marked clean in UoW
//but a nicer API would be something like this
$User->save();
//but if I want to do this - it has to make a call to the mapper/db somehow
$User->getBlogPosts();
//or else have to generate specific collection/object graphing methods in the mapper
$UserPosts = $UserMapper->getBlogPosts();
$User->setPosts($UserPosts);
关于如何处理这种情况的任何建议?
我不愿意将映射器/数据库访问的实例传递/生成到域对象本身以满足 DI - 同时,避免导致域对象内大量调用外部静态方法。
虽然我想如果我希望“保存”成为其行为的一部分,那么在其构造中需要一个这样做的工具。也许是责任的问题,域对象不应该有保存的负担。这只是 Active Record 模式中的一个非常简洁的功能 - 以某种方式实现它会很好。
【问题讨论】:
标签: php oop model singleton dns