views:

57

answers:

2

It seems to me that the only difference is that Active Record has CRUD methods in data container class, and the Repository pattern uses separate class for data container and CRUD methods, but surely I'm wrong.

What are the differences between Active Record and Repository pattern? When should I use which pattern?

+1  A: 

Essentially, your assumption is correct. The repository and DAO patterns externalize persistance concerns while Active Record internalizes them. I've actually seen some implementations where active record classes were injected with a repository instance that provided their persistence concerns internally.

The biggest reason against using the Active Record pattern is simple, your domain objects shouldn't care how (or even if) they are persisted. The repository pattern provides persistence ignorance to your domain objects by externalizing persistence concerns and providing it as an external service.

DanP
+1  A: 

IMO, The Repository pattern helps to reduce the number of queries made to the database because it trains you to think in terms of transactions, and batching of commands, whereas with the Active Record pattern its easy to get carried away calling .save(), .fetch(), etc. with reckless abandon. Databases can be a big enough bottleneck in general, don't make it worse with unnecessary queries.

Jason Miesionczek