
Originally Posted by
TomB
This was something I struggled to grasp at first too. The biggest problem is that really, you'd need to do:
PHP Code:
$user = new User($db, 1);
I see, I thought that was a problem also, but after making a ton of websites, from 3 page sites to sites dealing with billions of records, I noticed that you will ALWAYS work with just one database object.
At first, I used to have my DB objects like you, but when optimization came, and had to move objects from one database to another, there was a TON of code to update.
Even if you have a master/slave setup, or get data from 15 different servers depending on what object your loading, you will never need more than one DB object.
So I made it static (singleton functionality, but with less typing / harder to unit test).
PHP Code:
# Var loaded from a configuration file
$dbLink = array (
'user' => '',
'password' => '',
'host' => '',
'link' => 'default',
'methods' => array('insert', 'update', 'delete'), # This is a master server
);
DB::connect($dbLink);
class User extends abstractDTO {
private $conf = array (
'dbLink' => 'default', # What DB link to use.
'cacheLink' => 'default', # What cache link to use.
'fields' => ...
...
);
}
Each object (ex: User) is linked to the DB link, so when it interacts with the database, it can chose the correct connection.
The reason I ended up moving the object functionality into the actual object (witch used to be a DTO, but now it's the data mapper & DTO in one) was because maintenance was easier with the two in one.
I worked in Java more than a year on a big project (alongside 11 big-shot developers), and we started with a very similar setup like yours here. It worked great for a few months, until the boss had a few ideas, and we had to re-factor some code. Once we started to re-factor the DTOs, we had to re-factor the mappers, to keep them clear (UserMapper deals with the User object, and so on), and that turned into a nightmare.
Eventually, programmers stopped re-factoring the mappers, and we ended up with ListMapper that returns a list of User objects, UserMapper that could return list of UserProperties and so on. Eventually, we created a mapper wrapper, so we can call any object through it (it would find the object type and call it's mapper, returning the results), but that didn't quite work either because there are always exceptions.
Basically, it was very hard to find out where is what, a problem that it's hard to have if your object's functionality is in that object.
Bookmarks