Magento 2 — Module — Override Class
1 min readJul 15, 2019
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
.