TransWikia.com

what is the best way to create a new instance for class?

Magento Asked by Bhavik on December 5, 2020

What is the difference or best way for creation instance of new class?

Object manager?

or

Define in to constructor?

3 Answers

Using __construct() method defined inside php file,

Demo example,

protected $_entityResource;
public function __construct(
    MagentoCatalogModelResourceModelAbstractResource $entityResource
) {
    $this->_entityResource = $entityResource;
}

Why we have to not used Object Manager inside file, please check community thread, ObjectManager

Correct answer by Rakesh Jesadiya on December 5, 2020

A bit late but still a very important aspect in magento2. There are 2 ways to create new instance of objects in magento2 professionally. One is constructor injection. Second one is using factory.

Using Object manager directly in code, should be avoided as much as possible.

The following article provides a good explaination of the 2 ways with example.

http://www.rosenborgsolutions.com/magento-new-class-instance.php

Using class constructor

use SomeCompanySomeModuleModelUserFactory;
use SomeCompanySomeModuleModelUser;

class InjectUsingConstructorParameters
{
    /** @var User */
    private $user;

    /**
    * @param User $user
    */
    public function __construct(
        User $user
    ) {
        $this->user = $user;
    }
}

Using factory

use SomeCompanySomeModuleModelUserFactory;
use SomeCompanySomeModuleModelUser;

class InjectUsingFactory
{
    /** @var User */
    private $userFactory;

    /**
    * @param UserFactory $userFactory
    */
    public function __construct(
        UserFactory $userFactory
    ) {
        $this->userFactory = $userFactory;
    }

    /**
    * @param string $userId
    * @return User
    */
    public function getUserDetails(string $userId): User
    {
        $user = $this->userFactory->create([
        'param1' => 'param1value'
        'param2' => 'param2value'
        ]);
        return $user->getUserById($userId);
    }
}

Never ever like this

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogModelProduct')->load($id);

Answered by Nadeem Sayyed on December 5, 2020

As per my opinion its better to use construtor instead of Object Manager. We should not use the ObjectManager directly! It defeasance the purpose of dependency injection. We can use ObjectManager, if there is no alternative.

Answered by Pankaj Sharma on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP