Magento 2 – How to Create Varien Object

magento2object

In magento 1 we can create varien object like this

$collection = new Varien_Data_Collection(); 
$varienObject = new Varien_Object();
$varienObject->setData($data);
$varienObject->setItem($item);
$collection->addItem($varienObject);

How to create object in magento 2?

Best Answer

In Magento 2 the Varien_Object equivalent is \Magento\Framework\DataObject. The class name was changed from Object to DataObject because object is a reserved word in PHP 7. So you could use something like:

$obj = new \Magento\Framework\DataObject();
$obj->setItem($item);

Update 2018

This answer intended to illustrate an answer the original question in the most succinct way possible and not in the context of a real code example. Although it did answer the question, \Magento\Framework\DataObject is the new Varien_Object, the implementation wasn't 100% in line with Magento 2 best practice. As @MatthiasKleine pointed out, Magento 2 best practice to create objects in your code is to use Magentos DI framework to inject a factory into your class via the constructor and use that factory to create your object. With that in mind, using DI to create a DataObject in your own code should look something like this:

namespace My/Module;

class Example {
    private $objectFactory;

    public function __construct(
        \Magento\Framework\DataObjectFactory $objectFactory
    ) {
        $this->objectFactory = $objectFactory;
        parent::__construct();
    }

    public function doSomething($item)
    {
        $obj = $this->objectFactory->create();
        $obj->setData('item', $item);
        //or
        $obj->setItem($item);
    }
}
Related Topic