我不确定标题是否是描述此问题的最佳方法。

这本书-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方法?

最佳答案

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

/**
 * @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是一个属性,同时确保设置脏标记。

10-07 17:21