DAO vs ActiveRecord methods


For me, DAO and its methods is faster than ActiveRecord and its methods, especially to fetch a large amount of data.

So my habit is to use DAO every time I know I’m going to fetch many rows.

I’m just wondering if it’s the good practice.

thanks to share your point of view concerning this topic.

Yes, that’s good practice.

If you use AR, it’s far easier to integrate it with all kinds of built-in methods like validation, widgets, etc.

I think it’s far cleaner and easier to read than plain queries. I’m only using queries for complicated things or when performance is an issue, like importing/exporting large amounts of data.

I mean how can you in general prefer:

$sql="SELECT * FROM entries where id=:id";




$data = $command->queryAll(); 


$data = Entries::model()->findByPk($id);

You’d prefer DAO over AR because it doesn’t require as much memory. ;)

If you have many small queries - mostly lookups - then it makes sense to use DAO instead of full-fledged AR objects.

That depends on a lot of things…

Creating an empty AR object and setting the result is extremely light…

but you could also have the best of both worlds ;)

$data = Entries::model()->findBySql("SELECT * FROM entries WHERE id = $id");

I do agree that it can be overkill to create a model just for checking if some setting is true or false…

In general, I think best practice is to use AR unless:

  • performance is an issue like massive update or indexing scripts

  • you need fine grained control using specific queries

  • you want to use DB functionality that is not present in AR

  • doing very small lookups of data

I’m using a mix, where I use AR when I need more.

PS: You can also specify which fields to select when getting AR. This can also be configured for relations.


but you can write it so, too:

$rows=Yii::app()->db->createCommand("SELECT * FROM entries where id=:id"<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/wink.gif' class='bbc_emoticon' alt=';)' />->queryAll(array(':id'=>$id));