克隆$ this来做链接。这是个坏主意吗?

时间:2016-07-28 13:29:27

标签: php chaining method-chaining cloning

我正在上课:

class StuffDoer{
   public function __construct(Dep1 $dep, Dep2 $dep2, array $array){
      $this->dep = $dep;
      $this->dep2 = $dep2;
      $this->array  = $array;
   }

   public function genericDoStuff($param){
      // Do stuff here...
   }

   public function doStuffForMark(){
      return $this->genericDoStuff('Mark');
   }

   public function doStuffForTim(){
      return $this->genericDoStuff('Tim');
   }

   public function doStuffForAlice(){
      return $this->genericDoStuff('Alice');
   }
}

几个月后,我被要求制作方法genericDoStuff($ param)以及依赖它的所有方法,在应用程序的单个部分中使用额外的参数。我没有改变依赖于genericDoStuff的每个方法的签名,而是最终得到了以下内容:

 class StuffDoer{
   public function __construct(Dep1 $dep, Dep2 $dep2, array $array){
      $this->dep = $dep;
      $this->dep2 = $dep2;
      $this->array  = $array;
   }

   public function forParameter($param){
      $self = clone $this;
      $this->param = $param;
      return $self;
   }

   public function genericDoStuff($param){
      if($this->param !== null){
         // Do stuff by taking param into account
      } else {
        // Do stuff stuffdoer does
      }
   }

   public function doStuffForMark(){
      return $this->genericDoStuff('Mark');
   }

   public function doStuffForTim(){
      return $this->genericDoStuff('Tim');
   }

   public function doStuffForAlice(){
      return $this->genericDoStuff('Alice');
   }

}

这样,我就可以在应用程序的单点中执行此操作:

$myStuffDoer = $serviceContainer->get('stuff_doer');
$myStuffDoer->forParameter('AAAARGHITBURNSGODHELPME')->doStuffForMark();
// Future usages of $myStuffDoer are unaffected by this!

所以我的问题是:出于任何原因,这被认为是不好的做法吗?

0 个答案:

没有答案