Abstract layers are a way of “hiding” lower level functionality from high level code.
Using abstraction layers in your PHP scripts that utilize any database is important. For starters it allows you to easily add in support for multiple database servers/formats, like MySQL, PostgreSQL, and even flat-file databases. Also, it can make it much easier to add in security measures.
Whenever I add in some sort of abstraction layer for database access I think of it in this way:

Level 1
Level 1 represents the regular functions for accessing the various types of databases. You shouldn’t have to add anything here, because all of this functionality should be built in or available via PHP libraries.
Level 2
Level 2 is where everything starts to become more and more complex. At this point I create wrapper classes for each database server. The classes all share common functions. You can also create some purely generic classes and create subclasses of them, the choice is up to you.
The functions will be used by the higher level code for accessing and managing the databases. Generally I create two classes, one for the actual database server management (which has basic functions like connect, disconnect, usedatabase, gettable, etc) , and one for table/database management (with functions like getrow, setrow, etc).
Level 3
In most major PHP scripts I make, I usually create a main class called “environment”, which controls the various aspects of the script and opens any connections we may need. In this case, environment will load in the classes for the various database severs. It will only use the one that we need (which is usually set in a configuration file). It will then create an instance of the database server’s class for use later on.
It may also connect to the database server and select the database to use, although this depends on the type of script I am making.
Level 4
Level 4 is your main application code. When you want to load or set some data you can call the generic functions. Your high level code should not depend on one database server or the other, instead it should depend on the common functions provided by the wrapper classes.
Concerns
Designing scripts like this can add in a lot of complexity and can increase the script’s size a lot. Also, you can suffer some speed issues if optimizations are not done.
Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply