Is there a use-case for singletons with database access in PHP?

后端 未结 11 1843
名媛妹妹
名媛妹妹 2020-11-21 06:44

I access my MySQL database via PDO. I\'m setting up access to the database, and my first attempt was to use the following:

The first thing I thought of is glob

11条回答
  •  终归单人心
    2020-11-21 07:38

    In your example you're dealing with a single piece of seemingly unchanging information. For this example a Singleton would be overkill and just using a static function in a class will do just fine.

    More thoughts: You might be experiencing a case of implementing patterns for the sake of patterns and your gut is telling you "no, you don't have to" for the reasons you spelled out.

    BUT: We have no idea of the size and scope of your project. If this is simple code, perhaps throw away, that isn't likely to need to change then yes, go ahead and use static members. But, if you think that your project might need to scale or be prepped for maintenance coding down the road then, yes, you might want to use the Singleton pattern.

提交回复
热议问题