Which is a better way to connect to a database

I am no expert, but I know you are right. Don’t use static methods, if you don’t absolutely have to.

Though, to make sure only one instance of an object is created, usage of a static class/method is most likely necessary ( I don’t know of any other way, but if someone else does, please do explain). That being said, you can “hide” the static single instantiation method too. (and why I linked to PHPTheRightWay: see factory pattern for example and as Lemon_Juice mentioned). Theoretically, with the factory pattern, you could even extend your PDO connection system to have multiple single connections to different databases.

As for DI. No, DI alone doesn’t stop the duplication of an object. To enforce single object instantiation, you will still have to have some sort of code set up to check if the object is already created or not. (and also why I referred to PHPTheRightWay’s singleton pattern). :wink:

Scott

1 Like