Magento 2 Preference
Magento 2 Preference is used for rewrites as like in in Magento 1. we can extend class using preference. powerful feature, but as responsible as Magento 1.  Basically, we can't attempt to rewrite the same class in two different modules. if we try than that can be conflict.

How we can create preference ? yes we can use xml file for the same. i am giving you brief for the same.

Let's Start with simple module creation.

app/code/Denish/Example/etc/
app/code/Denish/Example/Block/

for register a module we will need two files.


- module.xml
- registration.php

app/code/Denish/Example/etc/module.xml


<?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="Denish_Example" setup_version="2.0.0" />
</config>

app/code/Denish/Example/registration.php


<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Denish_Example',
__DIR__
);

for enable and install/upgrade module please refer previous post i have posted in MAGENTO 2 BASIC COMMANDS.


Now creating our own preference using di.xml


app/code/Denish/Example/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\ListProduct" type="Denish\Example\Block\Product\ListProduct" />
</config>


Now whenever code will ask for load ListProduct, preference will check and load Denish\Example\Block\Product\ListProduct instead of Magento\Catalog\Block\Product\ListProduct

That's it...!!!


Experienced Magento Certified Developer with a demonstrated history of working in the information technology and services industry. Skilled in SQL, PHP, XAMPP, jQuery, and Microsoft Office. Strong engineering professional with a Master of Computer Applications

0 comments:

Post a Comment

Popular Posts

Have You Any Questins Let Us Know.

Contact Us
DENISH VACHHANI
Ahmedabad India