DEV Community

Creating a Database Connection As Far As We Obey to OOP

Mert Simsek on August 09, 2018

In this post, we will learn a pretty database connection in PHP. We have to obey the OOP with this case. Firstly, i will have interface file in pro...
Collapse
 
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.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

Database appears to be singleton, but it's possible to freely create instances of Database via public constructor.

IconnectionInfo provides getConnection() which returns a PDO object but Database also provides getSelectQueryResult()-method for results.

So it seems there's one responsibility too much. Do you want to provide users with database connections or get them results from the database? (Also, i think you should move the code from the constructor inside getConnection().)

Whichever responsibility you choose, i feel it would be more beneficial to provide a Database interface. This interface could be implemented by classes like PostgreSQLDatabase, MySQLDatabase, SQLiteDatabase etc. These implementations could take connection information as arguments because hard coding them is a bad practice.

Interfaces shouldn't be used as configuration. They should have no direct effect on the implementations internals.