Here is the plugin i created for limiting 3 products can be added into comparison. But it not loading, add one know what is the problem?
etc/frontend/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\Controller\Product\Compare\Add">
<plugin name="LimitToCompareProducts"
type="Custom\TestCompare\Plugin\LimitToCompareProducts"/>
</type>
</config>
etc/module.xml
<?xml version="1.0"?>
<!--
/**
*
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Custom_TestCompare" setup_version="1.0.0"/>
</config>
Plugin/LimitToCompareProducts.php
<?php
namespace Custom\TestCompare\Plugin;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Catalog\Helper\Product\Compare;
class LimitToCompareProducts
{
const LIMIT_TO_COMPARE_PRODUCTS = 3;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* @var RedirectFactory
*/
protected $resultRedirectFactory;
/** @var Compare */
protected $helper;
/**
* RestrictCustomerEmail constructor.
* @param Compare $helper
* @param RedirectFactory $redirectFactory
* @param ManagerInterface $messageManager
*/
public function __construct(
RedirectFactory $redirectFactory,
Compare $helper,
ManagerInterface $messageManager
)
{
$this->helper = $helper;
$this->resultRedirectFactory = $redirectFactory;
$this->messageManager = $messageManager;
}
public function aroundExecute(
\Magento\Catalog\Controller\Product\Compare\Add $subject,
\Closure $proceed
){
$count = $this->helper->getItemCount();
if($count > self::LIMIT_TO_COMPARE_PRODUCTS) {
$this->messageManager->addErrorMessage(
'You can add the compared products under 3 item(s)'
);
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
return $resultRedirect->setRefererOrBaseUrl();
}
return $proceed();
}
}
registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Custom_TestCompare',
__DIR__
);