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!

3 Answers 3

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. Jun 17, 2020 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 Jun 18, 2020 at 17:41
  • Hi @MohitPatel, I have updated my answer. Many thanks for your kind words Jun 19, 2020 at 8:54
  • Thanks so much this answer most useful for beginners learners magento 2.One again thanks ... Jun 19, 2020 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 . Jun 17, 2020 at 21:58
  • thanks Sharath, appreciated Jun 18, 2020 at 8:10
0
  1. Difference between Repository and Factory: In Magento 2, a Repository and a Factory serve different purposes.
  • Repository: A Repository is responsible for abstracting data persistence operations and provides a way to interact with the underlying data storage (e.g., database). It provides a consistent API to perform CRUD (Create, Read, Update, Delete) operations on entities. Repositories are used to retrieve, save, and delete entities without exposing the underlying data storage details. They ensure proper data encapsulation and help maintain separation of concerns. Repositories should be used when you need to perform data retrieval or modification operations.

Example of using a repository:

use Magento\Catalog\Api\ProductRepositoryInterface;

class ExampleClass
{
    private $productRepository;

    public function __construct(ProductRepositoryInterface $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function getProductById($productId)
    {
        $product = $this->productRepository->getById($productId);
        // Perform further operations with the retrieved product
        return $product;
    }
}
  • Factory: A Factory is responsible for creating instances of classes. It provides a way to instantiate objects and manage their dependencies. Factories are used to create new instances of objects when needed, especially for classes that have complex dependencies. Factories are typically used when you need to create a new instance of an object.

Example of using a factory:

use Magento\Catalog\Model\ProductFactory;

class ExampleClass
{
    private $productFactory;

    public function __construct(ProductFactory $productFactory)
    {
        $this->productFactory = $productFactory;
    }

    public function createProduct($data)
    {
        $product = $this->productFactory->create();
        $product->setData($data);
        // Perform further operations with the newly created product
        return $product;
    }
}
  1. Difference between Plugin and Observer: In Magento 2, both Plugins and Observers provide a way to modify or extend the behavior of existing code, but they are used in different scenarios.
  • Plugin: A Plugin (also known as Interceptor) allows you to intercept the execution of public methods of a class and modify their behavior by adding your custom code before, after, or around the original method. Plugins are used for cross-cutting concerns such as logging, caching, or modifying input/output. They provide a way to modify the behavior of a class without directly modifying its code.

Example of using a plugin:

class ExamplePlugin
{
    public function beforeExecute(\Magento\Catalog\Controller\Product\View $subject)
    {
        // Perform some code before the original method is executed
    }

    public function afterExecute(\Magento\Catalog\Controller\Product\View $subject, $result)
    {
        // Perform some code after the original method is executed
        return $result;
    }

    public function aroundExecute(\Magento\Catalog\Controller\Product\View $subject, callable $proceed)
    {
        // Perform some code before the original method is executed
        $result = $proceed();
        // Perform some code after the original method is executed
        return $result;
    }
}
  • Observer: An Observer listens for specific events dispatched by the Magento system and performs some action in response to those events. Observers allow you to react to certain events or state changes within the system. They are used when you need to perform additional actions based on specific events, such as updating database records, sending notifications, or modifying data.

Example of using an observer:

class ExampleObserver implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // Perform some actions in response to the event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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