PHP database class pattern questions/suggestions
I am developing my own class model for my database and I would like to know what you guys think of it.
For each table 开发者_如何学Goin my database I have 2 classes. The first one, is a fetching class (I don't know how to call it..), this class has some static methods interacting with the database (fetchAll, fetchById etc..). The second class is the model itself, it contains all methods for a row of the table (insert, update, delete, validate or any other processing on the row).
Each of the fetching class returns the model object, if it's a fetchAll, for example, the method will return an array of model, and if its a fetchById the method will return only 1 object, since id is unique.
Example of how I would use it :
$users = Users_Map::fetchAll();
foreach($users as $user)
{
echo $user->username.'<br/>';
}
$user = new User_Model();
$user->username = 'example';
$user->insert();
$user = User_Map::fetchById(1);
$user->username = 'example2';
$user->update();
If you have any suggestion other than _Map
, I'm open.
I'd like to know if this “pattern” is good and what do you think of it, how can I improve it, am I wrong? Should I use only 1 class, having static and non-static method all in the _Model
?
Thank you very much for your help/suggestions!
Sounds reasonable from what you've described, though the true test will come when you start seriously extending it.
I usually build a core of three classes:
- a database handler
- a generic object handler
- a generic collection handler
Each table gets one derived from the object class to represent one row in the table, and a class derived from the collection which represents some or all of the table and will return individual objects as requested. There is also a static "registration" function for seting up all the necessary information (table name, valid fields, etc) once for each class.
Sometimes, a collection class is also an object for another table. The generic objects and the registration mechanism I wrote ages ago seamlessly handles this.
That's the model I use in many of my applications, though for simplicity I combined the fetch-style methods into the same class as the insert()
-type methods. This is particularly easy to do in PHP 5.3 with late-binding static members, so you your superclass-defined fetchById
map can access the subclass-defined table_name
variable (for example).
精彩评论