Would singleton be a good design pattern for a microblogging site?

后端 未结 3 1423
一整个雨季
一整个雨季 2021-01-15 07:52

I have not used any OO in the past in projects, as I kept it simpler (in fact using archaic mysql_query calls and my own filtering), so I wanted to start a new project, lear

3条回答
  •  难免孤独
    2021-01-15 08:06

    As said before, the singleton doesn't help you with your blog application much. Just create a single database instance and use it.

    Sidenode, what you see in PHP are often "fake singletons". If implemented as plain class, it usually involves using a ::getInstance() method which implements the singleton workaround. The existence of the class however allows to instantiate multiple items (new Singleton() && new Singleton()). Therefore I'd recommend a procedural singleton, which doesn't have this problem and is also much nicer on the eyes:

     function db() {
         static $db;
         if (!isset($db)) {
              $db = new PDO("sqlite:memory");
         }
         return $db;
     }
    

    This way you can use db()->query("SELECT * FROM blog") and avoid to always import a global $db var.

提交回复
热议问题