原则设置方法成对API调用的最佳实践


Doctrine setter method best practice for paired API call

我有一个跟踪存储在第三方数据库中的客户状态的表。只有当我可以通过API调用成功地更新其他数据库时,我的表才应该被更新。

使用Doctrine时,将API调用添加到实体类的setter方法中是一种不好的做法吗?例如:

public function setCustomerStatus( $cusotmerStatus )
{
   $api = new externalApi();
   if( $api->updateStatus( $customerStatus ) )
   {
      $this->customerStatus = $customerStatus;
   }
   else
   {
      return 'Could not update customer status';
   }
}

如果你有一个只能在特定条件下设置的Entity字段,你有两个选择;要么在更新前检查:

if($api->updateStatus($customerStatus){
    $entity->setCustomerStatus($customerStatus);
}

或者,在Entity中进行检查,就像在set方法中所做的那样。在set方法中包含它的好处是不会给错误留下余地;不熟悉的开发人员可能不知道在调用set方法之前运行检查,或者您可能忘记了。因此,如果您能保证总是需要进行检查,我更喜欢您选择的选项