How to create varien object in magento 2?
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);
}
}
Instead of creating the object with 'new' you should use DI (Dependency Injection) to inject the Factory class and use that factory to create new instances of DataObjects.
/**
* @var \Magento\Framework\DataObjectFactory
*/
private $dataObjectFactory;
public function __construct(
// ...
\Magento\Framework\DataObjectFactory $dataObjectFactory
) {
parent::__construct();
$this->dataObjectFactory = $dataObjectFactory;
}
public function yourCode()
{
$dataObject = $this->dataObjectFactory->create();
}