I know you should now init object using new keyword as it surpasses the DI

But in few cases in core code is have observed the use of new keyword like in class module-catalog/Helper/Product

Do any one know what is difference b/w when you do

 if (is_array($buyRequest)) {
            $buyRequest = new \Magento\Framework\DataObject($buyRequest);


when you create its object using constructor and use setData()

Looking difference in case of use why and When you should NEW and when should you call Via DI .

1 Answer 1


It is because sometimes you need more than one instance of this class for different object in the same class.

For example in module-catalog/Helper/Product here you have two different variables that are of type \Magento\Framework\DataObject ($params and $buyRequest) but they are distinct variable that should not share the same object instance.

public function addParamsToBuyRequest($buyRequest, $params)
        if (is_array($buyRequest)) {
            $buyRequest = new \Magento\Framework\DataObject($buyRequest);
        if (is_array($params)) {
            $params = new \Magento\Framework\DataObject($params);

        // Ensure that currentConfig goes as \Magento\Framework\DataObject - for easier work with it later
        $currentConfig = $params->getCurrentConfig();
        if ($currentConfig) {
            if (is_array($currentConfig)) {
                $params->setCurrentConfig(new \Magento\Framework\DataObject($currentConfig));
            } elseif (!$currentConfig instanceof \Magento\Framework\DataObject) {
  • Don't we have factory Classes for it ? Oct 9, 2019 at 5:23
  • From magento 2 doc "Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity" devdocs.magento.com/guides/v2.3/extension-dev-guide/… . My guess here is that factories are used to create entities related to the database and the object related here are not database entities. Oct 9, 2019 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.