Video Lesson: Incorrect way to create objects with new keyword in Magento

Incorrect way to create objects with new keyword in Magento

Free Preview

Learn why the new keyword cannot create Magento objects and how dependency injection handles required class dependencies.


Lesson Content

We just learned why we shouldn’t use the new keyword in Magento, but let’s walk through an example to learn why.

We are currently just returning a die() function call in our controller’s execute() method, but that’s obviously not what we want to do. We want to instead return a regular Magento page response.

Creating an object with PHP is really easy. You just specify a class using the new keyword. We can see an example of this by using the new keyword to create a Session object. This Session class will be pulled from the Magento\Customer\Model.

Let’s output this to the screen using var_dump. We’ll also add an echo pre to make the output easier to read, and also add a die afterwards so our code execution stops.

<?php

declare(strict_types=1);

namespace Macademy\Blog\Controller\Post;

use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\HttpGetActionInterface;

class Detail implements HttpGetActionInterface
{
    public function execute()
    {
        echo '<pre>';
        var_dump(new Session());
        die();
    }
}

If we try to refresh this page though, we’ll see that an ArgumentCountError error that says “Too few arguments to function Page::__construct(). 0 passed in.

ArgumentCountError: Too few arguments to function Magento\Customer\Model\Session::__construct(), 0 passed in /var/www/html/app/code/Macademy/Blog/Controller/Post/Detail.php on line 13 and at least 21 expected in /var/www/html/vendor/magento/module-customer/Model/Session.php:138

So, this Session class is expecting us to pass in some arguments to it. Let’s go ahead and inspect this class, and we will see there is a LOT going on within this constructor. If you aren’t familiar with dependency injection, this is what is going on here. Classes are passed as arguments to constructors, and then they are assigned to class properties. Don’t worry much about this, as we’ll go over it in detail in just a minute. But, we cannot create an instance of this class in Magento using the new keyword, because it has all of these dependencies which must be created.

Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!