5

I have an observer checkout_cart_add_product_complete which gives me a product. But not the cart. I want to add data to the cart based on the product.

My observer definition.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_add_product_complete">
        <observer name="test_lease_controller_front_send_response_before" instance="Test\Lease\Observer\AddtoCart"/>
    </event>
</config>

The class:

<?php
namespace Test\Lease\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class AddtoCart implements ObserverInterface {
    public function execute(Observer $observer) {
        /** @var \Magento\Catalog\Model\Product\Interceptor $product */
        $product = $observer->getProduct();

        // need cart here
    }
}

I know the way to do this is dependency injection but I just can't figure it out.
I've red a few things but can't figure it out.

Can somebody help me get started?

1 Answer 1

14

I can't explain how it works. But Magento2 will autoload all classes passed specified in the __constructor. It will use reflection in some way.
I mostly copied \Magento\Wishlist\Observer\AddToCart, which observed the same event. The result:

<?php
namespace Marissen\Lease\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

use \Magento\Checkout\Model\Session as CheckoutSession;

class AddtoCart implements ObserverInterface {

    /** @var CheckoutSession */
    protected $checkoutSession;

    /**
     * @param CheckoutSession $checkoutSession
     */
    public function __construct(CheckoutSession $checkoutSession) {
        $this->checkoutSession = $checkoutSession;
    }

    public function execute(Observer $observer) {
        /** @var \Magento\Catalog\Model\Product\Interceptor $product */
        $product = $observer->getProduct();

        /** @var \Magento\Quote\Model\Quote  */
        $quote = $this->checkoutSession->getQuote();
    }
}
2
  • 1
    FYI, Magento 2 has a "object manager" that will pass in the classes used as arguments for the __constructor method.
    – laketuna
    Commented Mar 21, 2016 at 15:12
  • Yes I've read about it like I stated in the question. I just don't understand it at all. Mage2 is still fresh, so no hurry.
    – janw
    Commented Mar 21, 2016 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.