:::: MENU ::::

Magento Knowledge Hub: Tutorials, Tips & Trends

Cookies Consent Popup

Magento 2: Repository vs Factory – Choosing the Right Approach

Magento 2 offers several ways to work with models and data. Two of the most common are Repositories and Factories. Knowing when to use each helps you write cleaner, upgrade‑safe, and more efficient code.

What is a Repository?

A Repository is part of Magento’s Service Contracts layer. It implements an interface defined in the Api directory and acts as a public API for modules. Repositories ensure consistency and backward compatibility across Magento versions.

Key Points

  • Used for loading and managing existing entities.
  • Provides methods like getById(), getList(), save(), and delete().
  • Hides internal logic (EAV, joins, etc.) and exposes only the contract.

Example

$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->getById($productId);
   

What is a Factory?

A Factory is used to create new instances of entities. Since repositories don’t handle object creation, factories fill that gap by generating new objects that can later be saved through repositories.

Key Points

  • Factories are auto‑generated by Magento (e.g., ProductFactory).
  • Used to create new objects before saving them via a repository.
  • Respect dependency injection and create the correct implementation automatically.

Example

$productFactory = $objectManager->get(\Magento\Catalog\Api\Data\ProductInterfaceFactory::class);
$product = $productFactory->create();
$product->setSku('test-sku');
$product->setName('Test Product');
$productRepository->save($product);
   

When to Use Repository vs Factory

Use Case Repository Factory
Load existing entity ✔️ getById(), getList() ❌ Not suitable
Create new entity ❌ Cannot create ✔️ Use create()
Save entity ✔️ save() ❌ Must pass to repository
Delete entity ✔️ delete() ❌ Not applicable

Collections vs Repositories

Repositories are the official way to interact with entities, but they can be restrictive. For advanced queries, developers often use Collection Factories for more control over attributes and joins.

Example

$collection = $collectionFactory->create();
$collection->addAttributeToSelect(['name', 'sku']);
$collection->addFieldToFilter('status', 1);
   

Best Practices

  • Use repositories whenever they provide the needed functionality.
  • Create new entities through factories, then save them via repositories.
  • Use collection factories only when repositories are too limited.
  • Avoid using $model->load() directly — it’s not part of service contracts.
  • Always code against interfaces (ProductRepositoryInterface, ProductInterfaceFactory) for upgrade safety.

Conclusion

In Magento 2, repositories and factories serve distinct but complementary roles. Repositories handle loading, saving, and deleting entities, while factories create new ones. Collections are useful for complex queries. Following these patterns keeps your code clean, efficient, and aligned with Magento’s architecture.

Happy coding and clean architecture!

0 comments:

Post a Comment