PHP Database Class – Building an Abstract Database Class in PHP

abstract classArchitecturedatabasePHP

I wonder if I should write a database class for my application, and if so, how to accomplish it?

Over there on SO, a guy mentioned it should be written as an abstract class. However, I can't understand why this would be a benefit.

Do I understand correctly, that if I would write an abstract class, every other class that methods will need a database connection, could simply extend this abstract class and have its own database object? If so, how is this different from a "normal" class where I could instantiate an database object?

Another method would be to completely forget about my own class and to instantiate a mysqli object on demand.

What do you recommend?

Best Answer

Yes, you should use classes to access your database. A good link for further reading on that is to look up the Active Record Design Pattern and Object Relational Mapping

The benefit of this can be seen in the DRY Principle and the Law of Demeter question which was asked previously. By creating an abstract data access class, you keep the data access layer part of your application from leaking into your model/database entity classes AND you don't have to repeat yourself each time you have to make a new database model/entity.

Ok, so back to your question, so now, we build an abstract class to handle the CRUD for our database entities, so now, we only need to extend that abstract class and probably set some variables each time we add a new entity in the database. It makes the pain of writing SQL for your tables less annoying and much easier to handle by moving them all out to the abstract class as well as makes the data access layer of your application much manageable especially if you have a bazzillion models/database entities.

So whats the difference between making your abstract class and making a database model class then instantiating it with a database connection? Or the going straight to just using mysqli?

  1. With the abstract class, you only need to code the data access layer of your application ONCE
  2. Your code becomes DRY by eliminating the redundant database initializations
  3. Better maintainability, you only need to change one part of your code to change how you access the database!
  4. SQL Haters delight! They no longer need to directly touch SQL statements when dealing with ORMs

But as we are programmers, I would suggest not to rebuild this from scratch. No need to reinvent the wheel as they would say. There are already frameworks out there for PHP that handle ORM elegantly. You can look up popular MVC frameworks for PHP like Yii and Kohana.