Magento 2 – Understanding the $data Array Constructor Parameter

dependency-injectiondimagento2PHPpreference

So I noticed that in most models and blocks, there's this array $data = [] given as the last parameter of the constructor.

For example \Magento\Catalog\Block\Product\ListProduct

public function __construct(
    \Magento\Catalog\Block\Product\Context $context,
    \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
    \Magento\Catalog\Model\Layer\Resolver $layerResolver,
    CategoryRepositoryInterface $categoryRepository,
    \Magento\Framework\Url\Helper\Data $urlHelper,
    array $data = []
) {
    $this->_catalogLayer = $layerResolver->get();
    $this->_postDataHelper = $postDataHelper;
    $this->categoryRepository = $categoryRepository;
    $this->urlHelper = $urlHelper;
    parent::__construct(
        $context,
        $data
    );
}

I also know that, when dealing with preferences, you still have to keep that parameter in the end of your constructor parameters list when you add more parameters than the original constructor.

So I've got several questions regarding this array:

  • what is it ?
  • how to use it ?
  • why do we need to keep it at the end of the constructor parameters list when declaring preferences for a block that adds more parameters ?

Best Answer

The $data can be used to populate data on your object since the constructor of \Magento\Framework\DataObject is this

public function __construct(array $data = [])
{
    $this->_data = $data;
}

or similar for Magento\Framework\Api\AbstractSimpleObject

/**
 * Initialize internal storage
 *
 * @param array $data
 */
public function __construct(array $data = [])
{
    $this->_data = $data;
}

which a lot of classes in Magento extend from.

A common use is in conjunction with a factory. For example in Magento\Sales\Model\Order\CustomerManagement we have:

$this->addressFactory->create(['data' => $addressData]);

which essentially populates the $data array at creation.

Having to keep the $data = [] at the end of the list of parameters is normal php behaviour since you are assigning a default value - the empty array.