Pregunta

I have a class that extends \Magento\Customer\Block\Account\Dashboard\Info and I want to extend its constructor to get customer session, but how do I extend constructor?

PhpStorm is highlighting my constructor I don't know why (the same constructor than a "regular" constructor of one of my custom block)

¿Fue útil?

Solución

This class constructor can be extended like any other PHP class constructor, just make sure to pass the same parameters that the extended \Magento\Customer\Block\Account\Dashboard\Info class is using.

In your case the Info.php constructor looks something like this:

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer,
    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
    \Magento\Customer\Helper\View $helperView,
    array $data = []
) {
    $this->currentCustomer = $currentCustomer;
    $this->_subscriberFactory = $subscriberFactory;
    $this->_helperView = $helperView;
    parent::__construct($context, $data);
}

So your class should look something like this:

<?php
namespace Vendor\Customer\Block\Account\Dashboard;

class InfoExtended extends \Magento\Customer\Block\Account\Dashboard\Info
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer,
        \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
        \Magento\Customer\Helper\View $helperView,
        array $data = []
    ) {
        // Your new properties here
        parent::__construct($context, $currentCustomer, $subscriberFactory, $helperView, $data);
    }
}

BTW, the class you're extending already exposes the current customer session as $currentCustomer property so you can probably use that without overriding the constructor.

Otros consejos

As @JavierVillanueva suggested in his answer, you don't need to define a constructor in your class, if it extends the class \Magento\Customer\Block\Account\Dashboard\Info.

You will get the customer instance by the call: $this->getCustomer() in your custom class.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top