3

我不确定标题是否是描述这个问题的最佳方式。

这本书 - http://apress.com/book/view/9781590599099 - 说明了工作单元模式的实现。它有点像这样。

class UoW(){
   private array $dirty;
   private array $clean;
   private array $new;
   private array $delete;

   public static function markClean(Entity_Class $Object){
   //remove the class from any of the other arrays, add it to the clean array
   }

   public static function markDirty(Entity_Class $Object){
   //remove the class from any of the other arrays, add it to the dirty array
   }

   public static function markNew(Entity_Class $Object){
   //add blank entity classes to the new array
   }

   public static function markDelete(Entity_Class $Object){
   //remove the class reference from other arrays, mark for deletion
   }

   public function commit(){
   //perform all queued operations, move all objects into new array, remove any deleted objects
   }
}

class MyMapper(){
  public function setName($value){
     $this->name = $value;
     UoW::markDirty($this);//here's where the problem is
   }
} 

(暂时忽略静态调用和依赖的问题)

作者指出,这种实现需要编码人员插入相关的 UoW 标记方法,并且这种对模式的选择性尊重可能会导致错误。现在,考虑到具体访问器的优缺点,您也许可以像这样自动化 UoW 调用:

public function __set($key,$value){
   //check to see if this is valid property for this class
   //assuming the class has an array defining allowed properties 
   if(property_exists($this,$key)){
       $this->$key = $value;
       UoW::markDirty($this);

       /*
       * or alternatively use an observer relationship 
       * i.e. $this->notify();
       * assuming the UoW has been attached prior to this operation
       */
      }
   } 

所以,我的问题是,当在域对象上设置属性时,你将如何保证调用适当的 UoW 方法?

4

1 回答 1

0

我发现的最佳方法是声明属性“受保护”,然后使用 PHPDoc 注释将它们“公开”为公共属性。就像是:

/**
 * @property string $prop
 */
class Foo extends UoW {
    protected $prop = "foo";

    public function __set($name, $value) {
        if (property_exists($this, $name)) {
            $this->$name = $value;
            $this->markDirty();
        }
    }
}

这将导致您的 IDE 和大多数工具获取 Foo->prop 是一个属性,同时确保设置了脏标记。

于 2013-07-25T07:49:58.763 回答