3

Yes, I know this question has many answers in google, but please clear my confusion.

  1. What is the difference between Repository and Factory, and when should We use a Repository vs a Factory in Magento 2?

  2. In Magento 2, what is the difference between plugin and observer? When should we use a plugin vs an observer in Magento 2?

  3. What is the difference between quote/quote Items and order/order Items, and when should we use one over the other?

If possible, please explain with a short example. We would be grateful to you!

10
  • Repository is the Model that is supposed to be used to expose the data for a given entity. In practice, they may optimise how the data is loaded. For instance, product repository uses a caching mechanism
  • Factory is used to create an instance of a Model that loads an entity (Magento auto-generates Factory class in generated folder)

similarity: they both lead to read/gather data for an entity

difference: if the entity is meant to be exposed with an API, the repository will be the model used whereas factory only loads data (and returns an object). Factory has more granularity than repository; meaning it is easier to customise the collection factory query than customising a repository getList method (playing with extension attributes is more abstract than playing with sql)

  • plugin is a way to intercept public functions for most classes in Magento. It can intercept before/around or after (as you well know indeed)

  • observer enables the developer to intercept a place in the system where the event for the observer is triggered.

similarity: they both intercept a place in the Magento system.

difference: plugin extends a class to customise its behaviour and observer extends the system by enabling additional logic/action to be happening within the observer. Observers are often more intricate to debug because they can spread the code logic amongst several places in the system whereas plugin follows the flow of features more naturally

  • quote/quote items: we use these anywhere in the frontend website when we want to interact with the items to be purchased in the customer session. items when we change product related info (price, tax, qty..) and quote when we interact with total for instance

  • order/order items: we use these mostly in checkout when the order is placed or customer order history and backend; order for dealing with order details (address, customer, total, status) and order items to read cart data for the order

differences: quote data are most often used for session data and order data for are used for data that have had a payment transaction/or payment commitment made against them

similarity: they both read data that are related to customer purchases. Most of the data structures are identical: customer, customer address, tax, cart, totals

Apologies, it is clear some people would make a better job for it but I'd thought I'd give it a go tonight, thanks for asking this question

UPDATE: Below is an example that shows how repository and factory get used and more importanlty how factory is very much hands-on whilst repository is more abstract

<?php

namespace Mbs\ProductListWithImage\ViewModel;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;

class ExampleRepositoryAndFactory
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    private $productRepository;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    private $productCollectionFactory;
    /**
     * @var FilterBuilder
     */
    private $filterBuilder;
    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        FilterBuilder $filterBuilder,
        SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->productRepository = $productRepository;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->filterBuilder = $filterBuilder;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    public function getProductByIds($productIds)
    {
        $collection = $this->productCollectionFactory->create();
        $collection->addFieldToSelect('small_image');
        $collection->addUrlRewrite();
        $collection->addFieldToSelect('name');
        $collection->addIdFilter($productIds);

        if ($collection->count() > 0) {
            foreach ($collection as $item) {
                // do things with product data
            }
        }

        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('entity_id', $productIds, 'in')
            ->create();

        $result = $this->productRepository->getList($searchCriteria);

        if ($result->getTotalCount()>0) {
            foreach ($result->getItems() as $item) {
                // do things with product data
            }
        }
    }
}
4
  • Thanks for your answer and i will read and update you. – Mohit Patel Jun 17 '20 at 18:15
  • Hello @Herve Tribouilloy i have read answer and brilliant answer.But if it is possible give me Repository and Factory small example – Mohit Patel Jun 18 '20 at 17:41
  • Hi @MohitPatel, I have updated my answer. Many thanks for your kind words – Herve Tribouilloy Jun 19 '20 at 8:54
  • Thanks so much this answer most useful for beginners learners magento 2.One again thanks ... – Mohit Patel Jun 19 '20 at 8:57
2

Herve Tribouilloy has done an excellent job in answering your questions! #Kudos

Let me add my 2 cents regarding some practical implication/considerations w.r.t Question # 2

2.) magento 2 difference between plugin and observer.And same When Should We Use a plugin and  observer in Magento 2.

In real-world scenario - the real distinction between the two DI mechanism is how/when to use them ... Typically:

  • Plugins are used in "I need to replace/modify an Out-Of-The-Box-Behavior with MY-CUSTOM-Behavior" scenario.

Note: If you want to COMPLETELY replace an OOTB behavior with your Custom-Behavior - you might want to consider using Preferences instead of Plugins.

  • Observers are used in a "I need to do XYZ if/when ABC occurs" scenario.

That being said - in Theory (atleast in most scenarios) - Plugins can be used to achieve what Observers do V/S Observers can't always do what Plugins do. ( Since, in most cases, you can write your plugin before/after/around methods to essentially override a Core classes behavior ... But, an Observer only kicks-in if/when the event being Observed is triggered. )

Even though it's easy to given into the One-Ring-To-Rule-Them-All Temptation and use Plugins everywhere - I highly recommend using:

  • Observers -> Plugins -> Preferences (In that Order)

Good Luck!

Cheers,

Sharath

2
  • Thanks,for your answer @Sharath Kumar . – Mohit Patel Jun 17 '20 at 21:58
  • thanks Sharath, appreciated – Herve Tribouilloy Jun 18 '20 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.