Magento 2
Using Object Manager
Free Preview
🟢 Good code
/**
 * Rather than using Object Manager directly in your code, instantiate objects
 * within the constructor of your class. This puts Magento in charge of
 * instantiating objects, and makes your code much more compatible with
 * third-party code, platform upgrades, & more.
 */

use Magento\Store\Model\StoreManagerInterface;
...
    /** @var StoreManagerInterface */
    private $storeManager;

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

    public function execute() {
        ...
        $quote->setWebsite($this->storeManager->getWebsite($websiteId));
        ...
🔴 Bad code
/**
 * Direct usage of Object Manager in your code is officially discouraged by
 * Magento. Calling the Object Manager inline (as below) circumvents Magento's
 * dependency injection layer, which automatically creates objects for you. This
 * leads to unsustainable code and is prone to errors during platform upgdates.
 */

public function execute()
{
    ...
    $quote->setWebsite(
        $this->_objectManager->get(
            \Magento\Store\Model\StoreManagerInterface::class
        )->getWebsite($websiteId)
    );
    ...
Want to learn more?

Visit M.academy to learn much more about Magento, Laravel, PHP, Javascript, & Docker.

M.academy logo