Virtual Type and Type

Blog
Spread the love

Virtual type is one of the most common design patterns in magento2. Basically, it allows us to modify existing classes without affecting other classes and inject them where we need them

Type allows us to modify dependencies injected to a constructor.

Consider following chunk of code:

We basically pass an object of our Bluethink\Crud\Model\ResourceModel\Post\Grid\Collection class to the Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory constructor of the bluethink_post_listing_data_source variable.

But type isn’t just about objects. It can be any value (e.g. array) that can be passed to the constructor.

has two attributes name and type, type is an existing class and name is virtual class (It does not need to create). Virtual types also can be used to manipulate the constructor argument of an existing class.

Consider following chunk of code:

The above code is almost same as creating a PHP class Grid:

Here is another chunk of code:

In the above example, We are modifying the constructor argument mainTable and resourceModel of class Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult

Consider you want to make a coffee for a party and each guest is told to bring a cup of coffee.

First, use the Espresso class in your code, where you’ll throw the coffee cups’ contents.

Now, you would put all coffee flavors into the Cup class:

Now collect the flavor cup and then move them into the Espresso. Let’s assume you first create 2 cups; one with Amaretto & chocolate and another with Hazelnut & Almond.

Next, we have our cups ready, let’s move them inside Espresso:

Conclusion: Now the cups are now in the espresso, and you are ready to make coffee 😉

Vikas Mishra

Vikas Mishra

2024-02-06

0

Leave a Reply

Your email address will not be published. Required fields are marked *

Find More Blogs

How to Add a Custom Tab to the Customer Order Detail Page in Magento 2

Spread the love Adding a custom tab to the Order Detail

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

bluethinkinc Blogs