What is the difference between type and virtualType – Practical Example

When we started working with Magento2, we found lot of the new features and new concept with it. One of the major and confusing the topic of the Magento2 is difference between type and virtualType.

I am not going to give any definition or theoretical explanation of both so lets just start with practical example and create one module which explain the same.

So our module will be very basic and it’s namespace will be Codedecorator and name of the module Learning. Let’s start with adding required file for module.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Codedecorator_Learning',
    __DIR__
);
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Codedecorator_Learning" setup_version="1.0.0" />
 </config>
<?php
namespace Codedecorator\Learning\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Codedecorator\Learning\Model\ClassDefault;

class Index extends Action
{
    protected $classDefault;

    public function __construct(
        Context $context,
        ClassDefault $classDefault
    )
    {
        $this->classDefault = $classDefault;
        parent::__construct($context);
    }

    public function execute()
    {
        echo "Index ClassA Namespace : ".$this->classDefault->namespace;
    }
}
<?php
namespace Codedecorator\Learning\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResponseInterface;
use Codedecorator\Learning\Model\ClassDefault;

class Submit extends Action
{
    protected $classDefault;

    public function __construct(
        Context $context,
        ClassDefault $classDefault
    )
    {
        $this->classDefault = $classDefault;
        parent::__construct($context);
    }

    public function execute()
    {
        echo "Submit ClassA Namespace : ".$this->classDefault->namespace;
    }
}
<?php
namespace Codedecorator\Learning\Model;

class ClassDefault
{
    public $namespace;

    public function __construct($namespace = 'default')
    {
        $this->namespace = $namespace;
    }
}

So, we have added two controllers and one model file. Please check Model file carefully. We have one class property and it’s default value is “default”.

We are trying to use this ClassDefault.php file in one our controllers and trying to print the property of model class.

If try to call the controller by url then we will receive the “default” for the both controller. For example:

calling 1st controller
Calling 2nd controller

As you see in above screenshot property name is coming default in both the controller so lets try to change the ClassDefault property default value without modifying the class directly and do so we can just need to add di.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <!-- Changing value for both Controllers  -->
   <type name="Codedecorator\Learning\Model\ClassDefault">
        <arguments>
                <argument name="namespace" xsi:type="string">test</argument>
        </arguments>
    </type>
 
</config>

As you noticed that we have used the type node and we have changed the namspace property from the default to test. Let’s flush cache as we have changed in the XML file and check the result.

Type node result.
Type node result

Yes, result changed and it is showing test instead of the default for both the controller.

I guess now you understand concept of type that it will change the property value for all the controller which is using the DefaultClass.php

If we want to change the property value for the Index.php controller and not for the Submit.php controller so here virtualType node comes in picture. It will allow us to create subclass and use that class wherever required. If you still have confusion check the updated di.xml and see the result.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <virtualType name="ClassDefaultVirtual" type="Codedecorator\Learning\Model\ClassDefault">
        <arguments>
            <argument name="namespace" xsi:type="string">test</argument>
        </arguments>
    </virtualType>

    <type name="Codedecorator\Learning\Controller\Index\Index">
        <arguments>
            <argument name="classDefault" xsi:type="object">ClassDefaultVirtual</argument>
        </arguments>
    </type>
</config>

You should flush the cache after making anything changes in XML files. Here is the result:

Result changed for the index controller
Default value came as it does not affect the submit controller

I hope this example makes helps you to understand the difference between the type and virtual type. Please leave a comment if you have any doubt.

Reasons Why You Should Choose Magento ECommerce Development

At some point, any initiative, no matter how big or small, will run into roadblocks. It may be a mental block for an author or a temporary pause in the progress of a project.

For example, eCommerce owners face challenges when creating their e-store, or, more precisely, when selecting an eCommerce Development platform, at the start of their online journey.

According to G2, there are 370 eCommerce sites to choose from. This can be a daunting number, and comparing and choosing from hundreds of choices is certainly a challenging job. Since your eCommerce site will be the cornerstone of every online company, you can’t afford to make mistakes.

Furthermore, there is no such thing as “the best” platform since each platform has its own set of benefits and disadvantages. It is entirely based on your criteria and additional goals that you wish to accomplish, and then you must select a platform that best suits your needs.

Do you believe this is a re-enactment of your conflict? If that’s the case, this article is for you!

So, let’s get started!

Is Magento eCommerce Production a common choice for most companies?

Every day, Magento receives 5000 downloads. According to reports, nearly 7,500 retailers moved to Magento from other eCommerce platforms last year. As a result, Magento is unquestionably the first choice of company owners dealing with a large number of consumers and profits, as well as those pursuing a long-term holistic solution. Because of its advanced features, inexpensive plugins, and rich functionality, it is a trusted forum for small business owners.

Are you aware that Magento powers famous eCommerce websites such as Nike’s and Samsung’s?

Overall, business owners prefer Magento, which explains why, by 2020, Magento is predicted to power more than 250,000 active eCommerce sites.

Is Magento eCommerce Production something you’d be involved in?

Let’s explore the advantages of Magento 2 Development Services to find an answer to this issue.

Scalability and increased efficiency

Any e-key store’s features are performance and scalability. Magento provides an interactive interface to ensure that everybody is on the same page. It includes an improved indexer that improves the web store’s query speed and efficiency.

What exactly does “high efficiency” imply?

1.End-users will note a decrease in the time it takes for a website to load.
2.Caching of the entire page
3. Indexing that is more effective

All of these factors contribute to your online store’s overall pace.

What does “improved scalability” imply?

Users now have the option of using several databases. You can also keep your checkout, order management, and product catalogue databases separate.

Advanced SEO Features

Online stores receive a lot of traffic from search engines. As a consequence, SEO is important for rising the site’s popularity and rating.

Magento 2 comes with an advanced SEO suite extension that will up the SEO game.

Take a look at the benefits of using an SEO suite:

  1. Create models for SEO.
  2. Configure your store’s rich snippets
  3. Manage tab, category, and layered navigation SEO settings.
  4. Automate the store’s Meta Tag management.
  5. With the aid of SEO toolbar, we can examine SEP sites.
  6. Set up canonical URLs
  7. XML sitemaps should be set up and configured.

Since SEO has the potential to increase traffic to your eCommerce store without costing a lot of money, you can draw high-quality traffic without spending a lot of money. As a result, you can select a forum that is SEO friendly. Wouldn’t you agree?

Mobile Friendly

The data on mobile shopping appears to be encouraging. For example, 79 percent of users have made an online purchase using their mobile devices in the last six months. This number is only going to grow as smartphones become more widely available. As a consequence, the eCommerce website must be compatible with mobile devices.

Magento 2 is a website that caters to smartphone users. It includes features that make it easy for customers to browse your store’s catalogue, as well as a mobile-friendly checkout process.

You can adapt new themes to physical and software device capabilities since Magento 2 is mobile sensitive.

The most important advantage is a higher rating for your website. Since Google indexes mobile-first by default, this is the case. In other words, Google indexes and ranks every page based on its mobile edition.

As a consequence, creating a mobile-friendly website would give you an edge in search engines.

Reduced Security Vulnerabilities

One of the most serious issues confronting the eCommerce industry today is cyber crime. According to data, online payment fraud would cost the eCommerce industry at least $25 billion by 2024. To keep hackers at bay, you must be careful as an eCommerce owner. And Magento 2 has you covered in this regard.

It provides password management tools that assist businesses in safeguarding customer information.

The escaping of data is controlled by certain conventions in Magento 2’s system.

The system’s read-only’ option prevents unauthorized users from accessing those files. In summary, the Magento 2 platform offers a wide variety of tools and features that help to reduce security risks.

Remarks at the End

Magento eCommerce production is used by 12% of all online businesses. The possibilities offered by this platform are infinite.

As a result of your decision to use this famous platform, your store can soon reach new heights. Will you want to know how to do it?