DEV Community


Discussion on: Creating a Database Connection As Far As We Obey to OOP

belinde profile image
Franco Traversaro

I strongly disagree with this approach.
Putting connection parameters on the interface is one of the dumbest things I've ever seen: what if you have to connect to two or more databases in the same time? Parameters have to be passed as, you don't say, parameters; use a configuration file or, even better, environment variables.
On the code: why you set private properties from interface constants while your class implements it? In the constructor you can simply use self::DBNAME.
You are trying to have a Singleton, so your constructor must be private. But Singleton are not a good choice: it's vastely considered the most harmful design pattern of the Gang of Four, and I agree. Try to seriously do some unit testing and see.
PDO is already object oriented. Having a private instance is useful only if you are planning to create adapters, different classes for different databases; but PDO can connect to a lot of DBs, so you could simply extend the class PDO, override the constructor if you want manage the parameters in some smart way (but it's better take just the connection string and leave the burden of the organization to the project that will use the class) and add your commodity methods. THAT's OOP.