1

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);
        }

VS

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 .

0

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) {
                $params->unsCurrentConfig();
            }
        }
  • Don't we have factory Classes for it ? – Vishwas Bhatnagar Oct 9 '19 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. – Carlo Ricci Oct 9 '19 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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