How to extend magento part 2

Using magento plugin feature you can avoid extending class and adding your own custom logic.

In order to achieve our task we will do the following. Create a class on your own and inject whatever dependencies you need for this class (using best practice).

class MyCustomPlugin
    // before execute method of \Magento\Checkout\Controller\Cart\Add is called, I will be called
    public function beforeExecute(Add $controller): Add
        // if some error takes place, do not add product to the cart
        if ($exception) {
            // \Magento\Framework\Message\ManagerInterface
            $controller->getRequest()->setParam('product', false);

        // otherwise let it pass smoothly
        return $controller;

The benefits of using this approach are the following:
1) If you upgrade magento version, it will have zero or minimal effect. This is a very important point for using this kind of development approach.
2) You can easily unit test this plugin
3) You did not extend magento base class, which is a bad practice

Now you need to tell magento to pick up this file, in your project.

add this to di.xml to inform magento about our plugin

<type name="Magento\Checkout\Controller\Cart\Add">
    <plugin name="somepluginname"

More information on plugins you can find on this page from magento.

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news


PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.