If I had my products stored like this:
tbl_products
id, price, stock
1, 20, 5
2, 30, 5
And the texts are on another table:
tbl_texts
id, item_id, type, field, value
1, 1, 'product', 'name', 'Programming Book'
2, 1, 'product', 'description', 'A fine book'
3, 2, 'product', 'name', 'Bicycle'
4, 2, 'product', 'description', 'Goes very fast'
And the campaign prices are on another table too:
tbl_product_campaign_prices
id, item_id, price, valid_from, valid_to
1, 1, 5, null, null
2, 2, 10, null, 2014-10-10
Okay, there's my imaginary tables.
I'd like to handle the products as objects and since I don't always want to get all data related to the products because it's database heavy and I rarely need to access all of it.
For example, sometimes I only need the name or description of a product. Sometimes I need the campaign prices. The base info on the tbl_products would be fetched always.
The real question is; what are my options on the code. I came up with a few:
1.
$product_id = 1;
$fetch_name = 1;
$fetch_description = 0;
$fetch_campaign_prices = 0;
$product = ProductFactory::get($product_id, $fetch_name, $fetch_description,
$fetch_campaign_prices);
// This takes a lot of space and is very impractical
// when I have to add new data to be fetched.
// Worst case would be having to add a bunch
// of null, null, null to get the last data.
2.
// Same as 1. but adding all the $fetch_ into an array and only use 2 parameters on the
// get() function.
$product = ProductFactory::get($product_id, $fetch_array);
// Still pretty ackward way to fetch data but much easier to add stuff
// since I don't have to add any new parameters
3.
$data_to_fetch = array('name', 'description');
ProductFactory::Prepare($data_to_fetch);
$product = ProductFactory::get($product_id);
Is there a common way to do this? An efficient way to do this? I've never done anything like this and these are from the top of my head.
Thanks for your upcoming input!
$product = ProductFactory::get($product_id, FETCH_NAME | FETCH_PRICES);
– Mark Baker Oct 1 '13 at 11:44