2

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

Object manager?

or

Define in to constructor?

0
3

Using __construct() method defined inside php file,

Demo example,

protected $_entityResource;
public function __construct(
    \Magento\Catalog\Model\ResourceModel\AbstractResource $entityResource
) {
    $this->_entityResource = $entityResource;
}

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

1

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.

1

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 SomeCompany\SomeModule\Model\UserFactory;
use SomeCompany\SomeModule\Model\User;

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

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

Using factory

use SomeCompany\SomeModule\Model\UserFactory;
use SomeCompany\SomeModule\Model\User;

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 = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);

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.