Magento 2 — Module — Override Class

To override Classes on Magento 2 Module, We need to make the class, example we create a class Block/Override/ReplaceWithThis.php and extending Class which will be replaced/overridden. e.g. in this case, wa want to override Block/PostCategory.php. Then,we need to write Block/Override/ReplaceWithThis.php with this code:

<?phpnamespace VendorName\ModuleName\Block\Override;use \VendorName\ModuleName\Block\PostCategory;class ReplaceWithThis extends PostCategory
{
public function exampleMethod()
{
return __('Hello everyone!');
}
}

Next configure to replace PostCategory class with ReplaceWithThis class by making etc/di.xml file:

<?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="VendorName\ModuleName\Block\PostCategory" type="VendorName\ModuleName\Block\Override\ReplaceWithThis" />
</config>

Explanation:

  • for : what class will be overridden.
  • type : this class will override for syntax.

Finally, execute this on command line bin/magento setup:di:comile.

I wrote these tutorials for myself in future when I forget for the next steps.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store