My question is, how can I separate the database connection from the application model level? The main problem is to be able to easily change databases of different types. You might start with a flat file, a comma-delimited database. Then you want to go to the SQL database. Then you decide that the LDAP implementation will be better. How can a person easily plan something like this?
For a simple example, suppose you have a user with a first name, last name, and email. A very simple PHP class representing it might look like this (please ignore problems with public instance variables):
<?php class User { public $first; public $last; public $email; } ?>
I often saw where people have a DAO class that has built-in SQL in it:
<?php class UserDAO { public $id; public $fist; public $last; public $email; public function create( &$db ) { $sql = "INSERT INTO user VALUES( '$first', '$last', '$email' )"; $db->query( $sql ); } } ?>
My problem with such strategies is that when you want to change your database, you have to change each DAO class, create, update, load and delete functions to work with your new database type. Even if you have a program to automatically generate them for you (which I am not a fan of), you will have to edit this program to work now.
What are your suggestions on how to handle this?
My current idea is to create a superclass for DAO objects with its own create, delete, update, load functions. However, these functions will take arrays of DAO attributes and generate the request itself. So the only SQL is in the SuperDAO class, and not scattered across multiple classes. Then, if you want to change your database level, you will need to change the way you generate SuperDAO queries. Benefits? Disadvantages? Foreseeable problems? Good, bad and ugly?
database php design-patterns abstraction orm
Marshmellow1328
source share