【问题标题】:How to copy a CakePHP Entity如何复制 CakePHP 实体
【发布时间】:2016-01-15 18:16:01
【问题描述】:

我正在编写一个复制对象的方法。与其手动设置每个属性,不如仅循环遍历原始对象的属性会更加健壮...

//Booo
$new->name = $old->name;
$new->color = $old->color;
...

//Oh yeah...
foreach ($old as $prop=>$val){
    $new->$prop = $val;
}
unset $new->id;

CakePHP 实体似乎无法以这种方式进行迭代。我尝试使用$old->toArray(),它基本上可以工作......但也有将所有关联转换为数组的缺点,这让我在下游搞砸了。

如何在不转换所有数据类型的情况下遍历 $old 属性?

更新: Mark 让我注意到__clone() 方法的存在。听起来它完全符合我的需要,但我仍在研究如何使用它。

【问题讨论】:

  • 如果您尝试复制对象上的所有属性,您可能需要使用clone
  • 谢谢马克!我无法在文档中找到它......它也会做关联吗?喜欢级联克隆?
  • @MarkStory 我更新了问题的标题,以更准确地反映我正在尝试做的事情。您的__clone() 提示听起来很准确...想要将其作为答案提交?

标签: php cakephp cakephp-3.0


【解决方案1】:

你可以使用 $entity->visualProperties()

foreach($old->visualProperties() as $property) {
    if($new->has($property))
        $new->set($property, $old->get($property));

【讨论】:

    【解决方案2】:

    看了一段时间后,发现没有实体的 __clone() 函数,至少在 3.8 中,我已经弄清楚了如何做到这一点,并得到了 DouglasSantos 的提示:

    //Find out the entity classname
    $classname = get_class($entity);
    
    //Instanciate a new object of that class    
    $clone = new $classname;
    
    //Use visibleProperties to clone it
    foreach($entity->visibleProperties() as $property)
        if($clone->has($property))
        $clone->set($property, $entity->get($property));
    

    当然,您可以将前 2 行合并为一行,但为了清楚起见,我已将其分开。

    更新:我发现如果您使用 has->($property) 检查它会跳过许多字段。所以正确的答案是:

    //Find out the entity classname
    $classname = get_class($entity);
    
    //Instanciate a new object of that class    
    $clone = new $classname;
    
    //Use visibleProperties to clone it
    foreach($entity->visibleProperties() as $property)
        $clone->$property = $entity->$property;
    

    【讨论】:

      【解决方案3】:

      实际上使用表格对象要容易得多:

      // Assuming your model is called "Documents"
      // If you are in the Controller, you can just use `$this->Documents`
         instead of fetching the Table from the Registry
      use Cake\ORM\TableRegistry;
      $table = TableRegistry::getTableLocator()->get('Documents');
      
      // newEntity() creates a new Entity from an array of data
      $documentCopy = $table->newEntity(
          // extract() extracts the given properties as an associative array
          $document->extract(
              // getVisible() will get all visible properties as an array
              $document->getVisible()
          )
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-22
        • 2018-11-05
        • 1970-01-01
        相关资源
        最近更新 更多