Magento 2 – What Does $this->hasData() Evaluate and Do?

magento-2.1magento2model

I've seen at several sites having the method $this->hasData('test'); in their Block classes (not template files).

As an example, here's an extract of a method in a Block class from a tutorial site:

public function getTestModel()
{
    if (!$this->hasData('test')) {
        if ($this->getTestId()) {
            /** @var \Aion\Test\Model\Test $test */
            $test = $this->testFactory->create();
            $test->load($this->getTestId());
        } else {
            $test = $this->test;
        }
        $this->setData('test', $test);
    }
    return $this->getData('test');
}

I've searched around for this method, but I can't exactly figure out what this function does. Why would I want to store $test through $this->setData('test', $test);? I could just store it in a class variable like $this->tmpTest = $test and return the class variable, couldn't I?

Looking up the Magento source, this is the comment docs of this method in DataObject.php:

/**
 * If $key is empty, checks whether there's any data in the object
 * Otherwise checks if the specified attribute is set.
 *
 * @param string $key
 * @return bool
 */

But what's $key and what attribute is this referring to?

What am I actually checking with the hasData() method? The example I saw took in the word test as its parameter but I have no idea what the word "test" relates to.

What is that parameter the $this->hasData() method actually takes in?

Why would I even want to use this method?

Best Answer

every class that extends the DataObject class contains a member called _data.
From here you can get the values using $this->getData('key_here').
That will return _data['key_here'].
The hasData method checks if that key is set.
For example $this->hasData('test') is an equivalent for array_key_exists('test', $this->_data).
Here is where the method is defined.

If your model is a flat table model (all values are kept in a single table) the key should be one of the column names.
For example when having a cms page model, $this->hasData('identifier') will check if the page identifier is set.
If the model is an EAV model, the key should be one of the entity attributes.
For example for products, $this->hasData('name') will check if the product name is set.

But, in general you can set anything to the _data member on any model using $this->setData('some_key', 'some_value').
In this case, the key can be any string.
Then you can check if the data for a certain key is set with $this->hasData('some_key');