Magento2 Preference

In Magento1, we used to override or rewrite the classes and the same concept is replaced by Preference in Magento2.
We can use the preference to override or rewrite the block, model, helper, controller.

Let's have an example to use preference as defined below:

Step 1: Create a registration file as module.xml in following location at Magento directory root.

Location: app/code/Magemeta/Related/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magemeta_Related" setup_version="18.0.1"></module>

Step 2: Create a di.xml file to declare the rewrite for the below block file.

Location: app/code/Magemeta/Related/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\ProductList\Related" type="Magemeta\Related\Preference\Related" />

Step 3: Create a Related.php file to override the file.

Location: app/code/Magemeta/Related/Block/Product/ProductList/Related.php

namespace Magemeta\Related\Block;

class Related extends \Magento\Catalog\Block\Product\ProductList\Related
* Get loaded items
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
public function getLoadedItems()

return $this->getItems();

We are done with the custom module for preference example.
Want to know about plugins in Magento 2, please go to the link now.

Leave a Reply