Magento 2 Plugin vs Preference – Basic Difference Between Plugin and Preference

magento2magento2-dev-betapluginpreference

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;
}
}

Best Answer

A preference is equivalent to class rewriting from Magento 1. It's equivalent to saying, "Whenever code asks for ClassA, give them MyClassB instead." MyClassB is expected to be a complete implementation of ClassA, plus whatever behavior you add or modify on top.

As in Magento 1, only one preference (rewrite) can be active for a class at one time unless you chain them manually (such that MyClassB extends OtherClassB, and OtherClassB extends ClassA).

A plugin allows you to execute code before, around, or after methods from the class you're hooking onto. Your plugin class does not replace the target class, and it is not an instance of it. You just have methods before{method}, around{method}, after{method} which get executed at the appropriate time in respect to {method} on the target class.

Since plugins do not replace the target class, any number of plugins can be active on a class simultaneously. Magento just executes them one after another based on the sortOrder parameter in your XML.

Because of that, plugins are much more flexible than preferences. You should use plugins whenever possible, and avoid preferences for rewriting classes unless absolutely necessary.

You can read more about how plugins work and how to use them in the official documentation.