如果我保存这样我的产品:PHP:高效的方式来使用对象作为产品数据库
tbl_products
id, price, stock
1, 20, 5
2, 30, 5
而且文本是在另一个表:
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'
而且竞选价格在另一张桌子上:
tbl_product_campaign_prices
id, item_id, price, valid_from, valid_to
1, 1, 5, null, null
2, 2, 10, null, 2014-10-10
好的,这里有我想象中的桌子。
我想将产品作为对象处理,因为我并不总是希望获得与产品相关的所有数据,因为它的数据库很重,我很少需要访问所有数据。
例如,有时我只需要产品的名称或描述。有时我需要竞选价格。 tbl_products上的基本信息将始终提取。
真正的问题是,我的代码选项是什么?我想出了几个:
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);
有没有做到这一点的常用方法?一个有效的方法来做到这一点?我从来没有做过这样的事情,这些都来自我的头顶。
感谢您的即将来临的输入!
选项#4 - 以设置错误级别或排序标志的方式传递一组位图标志:'$ product = ProductFactory :: get($ product_id,FETCH_NAME | FETCH_PRICES);' –
Mark有正确的愿景。 @MarkBaker,你为什么要发表评论?解决问题的最佳方法是使用位掩码。 –
@Michael - 主要是因为我认为,如果我可以用比tweet更少的字符回答问题,它只能作为评论 –