2
votes

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, learning to use design patterns with my OO along the way.

I was looking to build a microblogging site for kicks, and found the singleton design pattern class which seemed complete, and to use with PDO I could not see anything wrong with it (other than not being able to access two databases, which I am not sure I would need for this project).

On say a project like this, or a simple CMS software, would a singleton be a good idea? What sorts of design patterns/database class type would "the big guys" be using for these things, would this be too restrictive later on if it were to be upscaled (concurrent connections/performance)?

I had also read about a factory singleton to deal with dealing with extra connections later on as it is simpler to change the code in it. Would this fix any of the negative issues and make it a more suitable design pattern for this?

3

3 Answers

3
votes

The Singleton's purpose is to limit object instances to one and to provide global access.
Both are things you don't want or need.

Limiting your instance to one instance is rather pointless in PHP where this restriction only applies to the instances in the current request. If two requests hit your microblogging site at the same time, there will still be one instance each per request. If you want to make sure there is only instance, simply do not instantiate a second instance.

Global access is nothing you want either, because it breaks encapsulation. If you need a certain instance inside your objects, pass it in via dependency injection. That's clean and maintainable. It has the added benefit of allowing you to easily exchange dependencies with other implementations, like for instance mock classes for your unit tests.

Even Erich Gamma, one of the Singleton pattern's inventors, questions this pattern nowadays:

"I'm in favor of dropping Singleton. Its use is almost always a design smell"

You are best off avoiding Singletons.

2
votes

If I am not mistaken singleton is an antipattern. But depending on the task it can be used.

0
votes

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.