在幂等情况下通过服务更新实体的最佳方式?

the best way of update entity through a service in idempotent case?

假设我有实体:

class UserEntity
{
    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;


    /**
     * @var string
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @var string
     * @ORM\Column(type="string")
     */
    private $email;

// and contruct, getters and setters..

}

并在各自的服务中:

class UserService extends BaseService
{
    public function update($id, $data)
    {
        try {
            $user= $this->fetch($id);

            if (! $user instanceof UserEntity) {
                // throw respective exception;
            }

            $user->setName($data['name']);
            $user->setEmail($data['email']);

            $this->entityManager->flush($user);

            return $user;
        } catch (Exception $e) {
            throw $e;
        } 
    }
}

如果有这样的用户:

{
    id: 1,
    name: jhon,
    email: jhon@domain.com
}

提供给服务的数据是:

$id = 1;
$data = [
     'name' => jhon,
     'email => jhon@domain,com
]

那么,在这些情况下,避免对数据库进行不必要的查询的最佳方法是什么? 因为没有必要调用 flush 方法。 还是 Doctrine 内部负责不做查询?

根据 current docs:

The flush operation applies to a managed entity with the following semantics:

  • The entity itself is synchronized to the database using a SQL UPDATE statement, only if at least one persistent field has changed.
  • No SQL updates are executed if the entity did not change.

当实体成为托管时(根据它们的 ORMInvalidArgumentExceptions 之一):

An entity is managed if its fetched from the database or registered as new through EntityManager#persist

是的,Doctrine 会为您做决定。