mardi 10 mars 2020

PHP Repository pattern - update functionality

I am working on writing an update method, basically

class Entity {
 public $a;
 public $b;
}

class EnitityRepository {
 public function update(int $id, Entity $entity){
   $this->dao->update($id, $entity);
 }

 public function get(int $id){
   //does a look-up and returns an object of Entity
 }
}

class Dao {
  public function update(int $id, Entity $entity){
    $sql = "Update ABC";
    if(isset($entity->a) {
      $sql .= "set a = :a";
    }
    if(isset($entity->b) {
      $sql .= ", set b = :b";
    }
    $sql .= " WHERE id = :id";
  }
}

Now, in my dao, I want to update the record when there is no way to write conditional update (only update the values that are being set) as you don't know if a property on an object is set or not..and you can't just rely on empty or checking null as what if you really want to set the value as null.

would it be anti-pattern to use magic method __get, __set, __isset to refactor the Entity class like this?

class Entity {
  private $data = [];

  private $properties = [
      'a'      => true,
      'b'      => true,
  ];

  public function __set($name, $value) {
    if (array_key_exists($name, $this->properties)) {
      $this->data[$name] = $value;
    } else {
      //throw exception
    }
  }

  public function __get($name) {
    if (array_key_exists($name, $this->data)) {
      return $this->data[$name];
    }

    return null;
  }

  public function __isset($name) {
    return isset($this->data[$name]);
  }

  public function __unset($name) {
    unset($this->data[$name]);
  }
}

Or is there any better way than passing an array instead of an object in Dao.

Aucun commentaire:

Enregistrer un commentaire