I am looking for a best practice advice on how to use encapsulation when persisting collections of objects to the database.
For example, you need to persist a distributor which has a collection of products. If you keep encapsulation and don't mess up with database stuff relating to product tables in the distributor class you need to make too many hits to the database for saving each single product in a loop. The code would look like:
class Distributor {
private $products;
function save() {
foreach ($products as $prod) {
// 10000 products = 10000 hits to the DB! Instead of only one!
$prod->save();
}
}
}
On the other hand, if you would like to optimize the query and do a multiple row Insert/InsertUpdate you could do something more complicated like this:
class Distributor {
private $products;
$query = $dao->getInsertUpdateQueryInstance();
foreach ($products as $prod) {
// Much extra code for implementing such an encapsulation.
$query->addRow($prod->getRow());
}
$query->execute();
}
This would mean you need to write your DAO layer with specific functions as addRow().
The third possibility I see is to create a static array in the Product class, but this breaks the logical separation of concerns. Now the list of products is kept in the same Product class instead to be related to its distributor.
class Distributor {
// I'm a distributor and I have nothing to do...
}
class Product {
private static $products;
function save() {
foreach (self::products as $prod) {
// add row
}
// persist 10000 rows
}
}
Encapsulation, but so ugly! And what if you have several distributors? All products would remain in the same array?
Is there some non overcomplicated method to achieve this? Is ORM the only way to go?
There is no problem in writing a specific DAO for your Distributor. The second solution is fine, whereas the third solution should not be considered. Static is bad.
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With