I'm currently learning to code using OOP in PHP and have quite often come across database classes and abstraction layers. I'm coding a CMS as a big challenge and I started to code a database class without thinking about it too much.
I'm actually leaning towards using MySQLi as is (I think it's pretty good to use as is), rather than creating a class to deal with CRUD operations so do I really need a class to deal with all that stuff?
If not, what would be the best way of going about connecting to a database, just do it at the start of my application and pass the connection around? Or is there really a huge benefit of coding a database class that I'm missing?
I'm thinking that error handling would be one such benefit but if I'm keeping my class as close to MySQLi as possible, is that a good enough reason to go ahead with a class?
The main benefit is that if you can get all your code to go through your database objects. You can easily change the database implementation in the future. You say you are learning towards mysqli but say half way down the line you changed to PDO, you would have to refactor -everything-.
Using your custom database objects, you can simply alter the integration without effecting the rest of the code. E.g. Your objects->connect() function could still be called exactly as it is right now but the underlying code would change and as it was all within your custom class, the changes you make are minimal.
This is just one of many benefits. A custom class that interfaces with the database object to run queries and store results are quite common to see (the model part of an MVC - usually extending a common base object often called a RecordSet or similar that has functions to run select/update/delete/etc). As again, you can easily change the implementation from one method to another.
What I've described is a pretty common advantage for Object Orientated Programming in general. Please see Your Common Sense's answer for another good advantage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With