Magento – How is the array $data parameter set in Magento 2 (dataObject constructor)

dependency-injectionmagento2object-manager

In https://github.com/SnowdogApps/magento2-menu/blob/master/Block/Menu.php, a plugin that makes it possible to replace the default menu, the constructor of the block looks like below.

For all arguments / parameters in the constructor except array $data, my understanding is that those are somehow managed through the object manager and created if not existing. However, I'm stuck at figuring out how the array $data is set. In https://github.com/SnowdogApps/magento2-menu/blob/master/etc/di.xml, there is no argument named data.

Menu.php constructor:

public function __construct(
    Template\Context $context,
    EventManager $eventManager,
    MenuRepositoryInterface $menuRepository,
    NodeRepositoryInterface $nodeRepository,
    NodeTypeProvider $nodeTypeProvider,
    SearchCriteriaFactory $searchCriteriaFactory,
    FilterGroupBuilder $filterGroupBuilder,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->menuRepository = $menuRepository;
    $this->nodeRepository = $nodeRepository;
    $this->nodeTypeProvider = $nodeTypeProvider;
    $this->searchCriteriaFactory = $searchCriteriaFactory;
    $this->filterGroupBuilder = $filterGroupBuilder;
    $this->eventManager = $eventManager;
}

I've looked on this related question (Magento 2: what is the $data array constructor parameter?) and went to myMagentoRootFolder/vendor/magento/framework/DataObject.php, to have a look on the class which is inherited and uses the $data-parameter, this didn't make me understand it. Furthermore, I don't that the default empty array would work, because the getData()-method is used by the module and an empty response would be of no use.

DataObject.php constructor:

/**
 * Constructor
 *
 * By default is looking for first argument as array and assigns it as object attributes
 * This behavior may change in child classes
 *
 * @param array $data
 */
public function __construct(array $data = [])
{
    $this->_data = $data;
}

*Menu.php extends Template, and Template extends AbstractBlock, and AbstractBlock extends DataObject

So, I don't understand how and where array $data is set. Any help is appreciated, as I've been struggling to understand this for some days.

Best Answer

Data is set when instantiating the object, either through factory(preferred) or through object manager.

Factory:

$this->factory->create(['data' => ['key' => 'value']]); 

Object Manager:

$this->_objectManager->create(\Class, ['data' => ['key' => 'value']]);

Data can be set after instantiating the object by using setData

Related Topic