繁体   English   中英

PHP OOP:避免域模型模式中的单例/静态方法

[英]PHP OOP: Avoid Singleton/Static Methods in Domain Model Pattern

我理解依赖注入的重要性及其在单元测试中的作用,这就是为什么以下问题让我暂停:

我努力不使用Singleton的一个领域是Identity Map / Unit of Work模式(它保留了对象对象状态的标签)。

//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模式的一个很好的功能 - 以某种方式实现它会很好。

我做什么,尽管也许不是最好的行动当然是有我的课清晰的命名约定,FI: user_User是域对象和user_mapper_User是它的映射。

在我的父domainObject类中,我对逻辑进行编码以找到它的映射器。

然后你有几个选项委托给它,显而易见的是在domainObject使用__call()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM