I used both Plugin and Preference in Magento2 tutorial and both are working fine but what is the basic difference between them.
Code for plugin:
1.1) Add a plugin declaration into di.xml:
<type name="Magento\Catalog\Model\Product"> <plugin name="magento-catalog-product-plugin" type="Training\Test\Model\Product" sortOrder="10"/> </type> 1.2) Create a plugin class:
<?php namespace Training\Test\Model; class Product { public function afterGetPrice(\Magento\Catalog\Model\Product $product, $result) { return 5; } } Code for preference:
2.1) Create a preference declaration:
<preference for="Magento\Catalog\Model\Product" type="Training\Test\Model\Testproduct" /> 2.2) Create a new Product class:
<?php namespace Training\Test\Model; class Testproduct extends \Magento\Catalog\Model\Product { public function getPrice() { return 3; } }