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

后端 未结 3 1392
一整个雨季
一整个雨季 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:14

    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.

提交回复
热议问题