0

How in magento I can add something using plugin to result of a method. Having this dummy class and trying to change bar() methods return:

class A
{

    public function foo($str)
    {
        return $str;
    }

    public function bar()
    {
        return $this->foo('Some msg!!!');
    }

}

Thank you.

1 Answer 1

2

Example: add a string to getName() of Product class.

You have to create app/code/vendorName/moduleName/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">
    <type name="Magento\Catalog\Model\Product">
        <plugin name="plugin_name" type="VendorName\ModuleName\Plugin\Catalog\ProductAfter" />
    </type>
</config>

and app/code/VendorName/ModuleName/Plugin/Catalog/ProductAfter.php:

<?php

namespace VendorName\ModuleName\Plugin\Catalog;

class ProductAround
{
    public function afterGetName(\Magento\Catalog\Model\Product $product, $result)
    {
        return $result." string";
    }
}

The result is: the name of product + " string".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.