Lazy Loading Is Evil
#1
Posted 23 September 2012 - 06:01 AM
don't you think that AR lazy loading approach is evil?
#2
Posted 23 September 2012 - 07:35 AM

#3
Posted 23 September 2012 - 07:50 AM
Here's the example.
Controller:
$list = MyModel::model()->with(array('rel1', 'rel2', 'rel3', 'rel5'))->findAll();
View:
<? foreach ($list as $item): ?> <tr> <td><?= $item->rel1->name ?></td> <td><?= $item->rel2->name ?></td> <td><?= $item->rel3->name ?></td> <td><?= $item->rel4->name ?></td> <td><?= $item->rel5->name ?></td> </tr> <? endforeach ?>
As you have probably noticed, I forgot to add 'rel4' to 'with'.
And, because of my forgetfulness, bad things will happen.
And that brings me back to my original point: lazy loading is evil

#4
Posted 23 September 2012 - 09:44 AM
ORey, on 23 September 2012 - 07:50 AM, said:
....
And that brings me back to my original point: lazy loading is evil

eager loading and lazy loading both have their usage scenarios . if you always use eager loading that may cause memory and time waste . some time you don't need the "join" (you see the underlying story about the "with"

#5
Posted 23 September 2012 - 11:26 AM
If I want to use extra query , I prefer to do It manually

$project = Project::model()->findByPk($pid); $company = Company::model()->find('projectId = :pid', array(':pid' => $company->projectId));
There's no need to use lazy loading for this.
#6
Posted 24 September 2012 - 01:06 AM
#7
Posted 24 September 2012 - 03:03 AM
Usually I would start with lazy loading and will switch to eager loading if I think it's necessary. And, what I have to do then is just adding 'with'.
If referencing unloaded relation would have resulted in exception, it would be cumbersome to change loading manner between lazy and eager.
#8
Posted 24 September 2012 - 12:49 PM
Performance isn't always an issue. There are scenarios where some specific functionality of application (admin backend) or the whole application (intranet app) is available only for a few authorized users so database server is not likely to be overloaded.
#9
Posted 24 September 2012 - 01:14 PM
phtamas, on 24 September 2012 - 12:49 PM, said:
In a perfect world - yes.
In a real world we will have to move all the eager queries, like with('rel1', ..., 'relN'), to the model, right? Otherwise the controller will know the details about relations.
Quote
Speaking about business logic, we should create some methods like MyModel::getAllNeededData() and use only these methods.
And once we have done it, there's no difference on how the relations are loaded - using eager MyModel::model()->with('rel')->find or lazy MyModel::model()->find.
Quote
You're making me sad

#10
Posted 02 January 2014 - 02:57 PM
وقتی پیغام میذارید، بی زحمت متنتون رو انتخاب کنید و این دو تا کار ناقابل رو هم انجام بدید:
1. از اون بالا RTL رو انتخاب کنید.
2. فونت رو هم Tahoma بگذارید.
که چشممون در نیاد.
دمت گرم!
www.IranPHP.ir