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 thisor similar for
Magento\Framework\Api\AbstractSimpleObject
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: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.