cancel
Showing results for 
Search instead for 
Did you mean: 

Collection vs Repository

SOLVED
   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

Collection vs Repository

In the student guide I read that a collection returns a list of models and Repositories provide high level access to data. When I read this, I conclude that I should always return data and not models. In the core (several sales repos) I see returns of several models. Am I understanding this concept wrong or are there "possible exceptions"?

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Collection vs Repository

There are service contracts like https://github.com/magento/magento2/blob/develop/app/code/Magento/Customer/Api/CustomerRepositoryInt... - it is the external API for accessing a "repository". If you implement such a contract you should return data structures that implement the interfaces defined there. Those implementations will probably be classes (models), but could be just a separate class holding the data. As long as you implement the interface, the caller *should* not care. (People take short cuts!) Searches return things like \Magento\Customer\Api\Data\CustomerSearchResultsInterface at this level.

 

Collection is defined in Magento\Framework\Data\Collection (e.g. https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/Data/Collection.php)... is not part of the repository interface. It is a more low level API to access the database.

 

So a module frequently uses a collection to implement repository based service contracts.

View solution in original post

1 REPLY 1

Re: Collection vs Repository

There are service contracts like https://github.com/magento/magento2/blob/develop/app/code/Magento/Customer/Api/CustomerRepositoryInt... - it is the external API for accessing a "repository". If you implement such a contract you should return data structures that implement the interfaces defined there. Those implementations will probably be classes (models), but could be just a separate class holding the data. As long as you implement the interface, the caller *should* not care. (People take short cuts!) Searches return things like \Magento\Customer\Api\Data\CustomerSearchResultsInterface at this level.

 

Collection is defined in Magento\Framework\Data\Collection (e.g. https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/Data/Collection.php)... is not part of the repository interface. It is a more low level API to access the database.

 

So a module frequently uses a collection to implement repository based service contracts.