Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Active Record and Repository pattern?

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?

like image 290
Tom Pažourek Avatar asked Jul 25 '10 16:07

Tom Pažourek


People also ask

What is Active Record and ORM in rails?

1.3 Active Record as an ORM Framework Active Record gives us several mechanisms, the most important being the ability to: Represent models and their data. Represent associations between these models. Represent inheritance hierarchies through related models. Validate models before they get persisted to the database.

What is the repository pattern?

The Repository pattern. Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

What is Active Record TypeORM?

What is the Active Record pattern? In TypeORM you can use both the Active Record and the Data Mapper patterns. Using the Active Record approach, you define all your query methods inside the model itself, and you save, remove, and load objects using model methods.

What is active record pattern in laravel?

Active record pattern: The active record pattern is an approach to access data in a database, a database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table.


2 Answers

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.

like image 180
DanP Avatar answered Oct 29 '22 05:10

DanP


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.

like image 25
Jason Miesionczek Avatar answered Oct 29 '22 04:10

Jason Miesionczek