How to Override Core Block, Model & Controller in Magento 2
If you don’t know how to override a core model Block and controller in Magento 2. You’ve come to the right place. Although, it is a bad idea to override core classes in Magento 2, there are multiple ways to achieve this goal.
Let’s take an example of a list toolbar. You need to add a new sort option called “sort by most popular”. Magento 2 allows leveraging the concept of plugins to implement the improvement.
With the help of plugins, you can do whatever you want “after and before” the core function as well as “around”.
Create a di.xml file under Mymodule/etc/di.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <!-- /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> <type name="Magento\Catalog\Block\Product\View"> <plugin name="inroduct-custom-module" type="Sugarcode\Test\Block\Plugin\Product\View" sortOrder="1"/> </type> <type name="Magento\Catalog\Model\Product"> <plugin name="getname-test-module" type="Sugarcode\Test\Model\Plugin\Product" sortOrder="10"/> </type> </config> |
It illustrates Product Model and Product View Block.
Use “around” in the Product View block:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace Sugarcode\Test\Block\Plugin\Product; class View { public function aroundGetProduct(\Magento\Catalog\Block\Product\View $subject, \Closure $proceed) { echo 'Do Some Logic Before <br>'; $returnValue = $proceed(); // it get you old function return value //$name='#'.$returnValue->getName().'#'; //$returnValue->setName($name); echo 'Do Some Logic After <br>'; return $returnValue; // if its object make sure it return same object which you addition data } } |
In the model, use “before and after”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Sugarcode\Test\Model\Plugin; class Product { public function beforeSetName(\Magento\Catalog\Model\Product $subject, $name) { return array('(' . $name . ')'); } public function afterGetName(\Magento\Catalog\Model\Product $subject, $result) { return '|' . $result . '|'; } } |
Thus, you can retain the old code so every Magento core code update provides you with the new code and your custom logic.
Check