Skip to main content

Magento Fundamentals Part 3: What Are the Differences Between Collections and Repositories?

Image via Bitbull

One of the most frequent questions when manipulating entities in Magento 2 is, “Should I use a repository or a collection?”

In this article, we’ll share what the main differences between the two are.

We won’t go deep into the syntax details, but rather try to understand the pros and cons of both and when it’s better to use one over the other.


A brief definition of repositories and collections

Repositories were introduced in Magento 2, while collections are a legacy of Magento 1.

We use both to deal with entity persistence but from different abstraction layers.

Repositories are a higher abstraction that allow complete decoupling from the persistence layer.

According to Martin Fowler’s definition“a repository mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.”

Fowler doesn’t mention the domain by chance; repositories were first introduced as a part of Domain-Driven Design in 2004.

On the other hand, collections are a lower abstraction where a query is constructed, dealing more with database-related concepts and belonging to the resource models layer.

Being a higher abstraction, in Magento 2, repositories are often resource model wrappers and exposed as API resources.

The following is a simplified representation of the relations between layers: