Methods worth memorizing

Both EAV and simple models extend from the MagentoFrameworkModelAbstractModel class, which further extends from MagentoFrameworkDataObject. The DataObject has some neat methods worth memorizing.

Group of the following methods deal with data transformation:

  • toArray: Converts an array of object data to an array with keys requested in the $keys array
  • toXml: Converts object data into an XML string
  • toJson: Converts object data to JSON
  • toString: Converts object data into a string with a predefined format
  • serialize: Converts object data into a string with defined keys and values

The other groups of these methods, implemented through the magic __call method, enables the following neat syntax:

  • get<AttributeName>, for example, $object->getPackagingOption()
  • set<AttributeName>for example, $object->setPackagingOption('plastic_bag')
  • uns<AttributeName>for example, $object->unsPackagingOption()
  • has<AttributeName>for example, $object->hasPackagingOption()

To quickly put this magic into perspective, let's manually create the magelicious_core_log table as follows:

CREATE TABLE `magelicious_core_log` (
`entity_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`severity_level` varchar(24) NOT NULL,
`note` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`entity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

With the magic of DataObject, our empty MageliciousCoreModelLog model will still be able to save its data, as follows:

$log->setCreatedAt(new DateTime());
$log->setSeverityLevel('info'),
$log->setNote('Just Some Note'),
$log->save();

While this example would work, there is far more to it than this. Creating tables manually is not a viable option for building modules. Magento has just the right mechanism for this, which is called setup scripts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15