Thursday, December 29, 2016

Practical Magento 2: Creating a simple plugin

In Magento 1, when we wanted to override a specific method from the Core, we usually needed to rewrite Core class in our module.

Magento 2 introduced a new possibility for overriding core functionality without causing potential rewrite conflicts. It is called "Plugins".

For the purpose of this article, let's say that we want to modify product price displayed on the product view page. We want to override "getPrice()" method from \Magento\Catalog\Model\Product class.

In order to do that, we will add di.xml inside "Apiworks/Test/etc/frontend" folder with the following content:
(Apiworks/Test/etc/frontend/di.xml)

<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="productPriceAfter" type="Apiworks\Test\Model\Product\Plugin" />
   </type>
</config>
Inside the "type" node, we need to add an attribute "name" which represents original class whose function will be overridden by our plugin.

Plugin name = arbitrary name of our plugin.
Plugin type is our plugin class.

Next, we need to create our plugin class as we defined:
(Apiworks/Test/Model/Product/Plugin.php)

<?php
namespace Apiworks\Test\Model\Product;
class Plugin
{
    public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
    {
        return floatval($result / 1000);
    }

}
And that's it. We just need to clear the cache and visit the product page. Product price will have a value divided by 1000 in our case.

Except "afterSomeMethod", we also can use "beforeSomeMethod" and "aroundSomeMethod" in order to have great possibilities to modify original function input parameters, execution flow and return values as we did in our example.

Cheers.

, , ,

0 comments:

Post a Comment