I’m working on a Web App that queries data from a clients SQL Server database. The credentials to access said database are stored in a MySQL database on our server. Querying them separately really isn’t that hard, (Two letter difference with functions), but I recently had my “Oh god what a mess” moment and I’m trying to make things a little tidier.
In comes OOP. So now I’ve got basic CRUD classes in separate files for MySQL and SQL Server, but I feel like it’s totally not necessary to have two different includes for such similar (Two letters, come on…) functionality.
I tried to add both classes to one file, didn’t work.
So what’s the best best practice here?
Use a PDO object, with the relevant driver. There are drivers for MySQL and for MSSQL. Use a factory generate the right PDO object, and then use that object to actually write to the database.
For example (pseudo-ish code):
Your CRUD doesn’t care about which PDO it’s working with, only that it’s something with a PDO interface. If you change database again, you just update the database type. In addition, for unit testing, you can pass in a mock PDO.
One thing to bear in mind – not all databases offer the same functionality. Something can work in MSSQL that doesn’t work in MySQL. In this case, you can wrap the CRUD statement in an exception.
Also, consider looking at ORMs like Doctrine and Propel. They will teach you a lot, even if you choose not to implement them.