In various scenario's when I try to apply the *M*VC-pattern I can't seem to optimize this scenario where I have nested loops loading different kinds of models all having their own (single) query to load the entity from the database.
In the following code I've tried to describe such a scenario. As you can see, executing the same query 500 times doesn't look very promising for performance. Also making the OrderLine eager to fetch the product in the same query is not what I'm looking for, thought it would probably fix the illustrative scenario's.
Show all product stocks and reservation from the current open orders
// 1 query to get all open (undelivered) orders
foreach (Order::getOpenOrders() as $order) {
// for example; 50 open orders, so ~50 times this query
foreach ($order->getOrderLines() as $line) {
// for example; avg 10 lines per order, so ~50x~10= ~500 times this query
foreach ($line->getProduct() as $product) {
$stock = $product->getStock(); // ~500 times, heavy query
echo $product->getName().': '.$line->getAmount().' times ordered, '.
$stock.' times in stock';
}
}
}
I know things like caching could bring down the performance issue for 500 queries to a minimal, but it's just a example to illustrate the problem, not the impact of it.
I've thought of some different kind of solutions, but none of these does really fit the generic way I'd like to solve this problem:
- Doing something fancy with a Query builder, magically merging the different queries from the models into some kind of complex JOIN?
- Adding options to load the models in a transactional way. Not sure if possible and would become extremely complex I guess.
- Make models configurable for lazy/eager loading (difficult to code?)
- Creating custom methods for each of these scenario's, for example: Order::getSumAmountFromOrderLinesByProduct($product) // ;) Not very flexible and low maintainability. Also very different models become somewhat responsible for the (loading)behavior for other classes.
このマルチレベル/ネストされたモデルの読み込みの問題を解決するための最も一般的/最良の MVC 方法は何ですか?
また、この件に関するドキュメントやキーワードも大歓迎です。