samedi 3 décembre 2016

Using static method is bad practice, even with singleton?

I've read many posts said using static methods is bad practice. Many mentioned creating object with static methods but none of them remember about singleton.

I think using static methods is good sometimes especially with unique instance object like $db , $cookie , $session , $conversion ...

In the model layer, instead of passing $db around and separate model in two 2 classes, one is ModelService for communicating with db, one is ModelObject like this:

class ModelService {
  function __construct($db) {
    $this->db = $db;
  }
}

We can simply use singleton to access to db class using singleton and static method, i think it's useful in the Active record pattern

class ModelObject {
  function __construct($id, $name) {
    $this->id = $id;
    $this->name = $name
  }
  static function single() {
     $db = DB::getInstance();
  }
}

I think using instance is suitable for

Aucun commentaire:

Enregistrer un commentaire