Magento 2 Collections vs Repositories – Differences Explained

magento2

Please explain what is the difference between collections and repositories.

  1. What is the difference between those two?
  2. Which shall I use in custom module?

Best Answer

Collections

  • During development, if working with collections that have lot of attributes, filters, and possibly a future large dataset, we might want to use SQL logging to record actual SQL queries hitting the database server.

  • This might help us spot possible performance bottlenecks and react on time, either by adding more limiting values to setPageSize or addAttributeToSelect , or both.

Repositories

  • when you use repositories you adhere to Magento 2 service contracts, which means that service interfaces and data interfaces are defined (but extensible by third-party modules).
  • Making it possible at run-time to change the result of the call to the getList() method of a repository.
  • To retrieve the attributes you need at run-time you can use collections. Magento 2 framework itself makes an heavy use of collections.
  • Otherwise you should implement a module which defines a new data interface (that is, the new set of attributes) for that entity.

So Both we can use on our priority and our flexiblity.

Related Topic