Overwriting the Magento\Checkout\Controller\Cart\Add::getBackUrl with Plugin
Question
I've been trying to overwrite the getBackUrl method in the Cart Add controller of the checkout. With a preference I managed without an issue but plugins are a bit more of a challenge.
Here's what I have so far.
di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Controller\Cart\Add">
<plugin name="[namespace]_[module]_checkout_controller_cart_add_before" type="[Namespace]\[Module]\Controller\Checkout\Cart\Plugin" sortOrder="1" />
</type>
</config>
Controller/Checkout/Cart/Plugin.php
namespace [Namespace]\[Module]\Controller\Checkout\Cart;
class Plugin
{
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_config;
/**
* @var \Magento\Framework\Url
*/
protected $_url;
/**
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\Url $url
*/
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Url $url
) {
$this->_config = $config;
$this->_url = $url;
}
/**
* Get resolved back url, rewritten to return checkout URL instead of cart url
*
* @param \Magento\Checkout\Controller\Cart\Add $subject
* @return string
*/
protected function beforeGetBackUrl(\Magento\Checkout\Controller\Cart\Add $subject)
{
return $this->_url->getUrl('some/custom/url');
}
}
Whatever I try I can't get it to reach the beforeGetBackUrl
method.
Solution
It is possible to plug in to the public non-static methods only: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html#plugin-limit
It is impossible to plug in to the protected
, private
, static
methods.
Also it is impossible to plug in to the public __construct
method (constructor).
https://github.com/magento/magento2/issues/2265
https://github.com/magento/magento2/issues/2367
https://github.com/magento/magento2/issues/2202#issuecomment-151599087
OTHER TIPS
You cannot plugginize getBackUrl, but you can getUrl.
For this you need:
- Create virtual type myUrlBulder from \Magento\Framework\Url
- Use it as argument for \Magento\Checkout\Controller\Cart\Add
- Declare plugin for myUrlBulder virtual type