Magento create new object instance - best practice

There are 2 ways to create new instance of php objects in magento2 professionally.
1) Using factory
2) Using constructor parameters

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

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

Never ever like this

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);

Do not forget to run php bin/magento setup:di:compile after creating new class

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.