Magento 2
Create Model Instances with Factory Classes
Free Preview
app/code/Foo/Bar/Controller/Index/Index.php
<?php
namespace Foo\Bar\Controller\Index;

/**
 * Model entities in Magento are "non-injectable", meaning you can't use
 * dependency injection to create an instance of the entity.
 * 
 * While we have the ability to create Factory classes manually, we do not have
 * to, as Magento automatically creates them if they do not exist.
 * 
 * Import your model at the top of a class, and also import the related Factory
 * class. This class does not yet exist! But it will automatically at run-time
 * and placed at generated/code/Foo/Bar/Model/BazFactory.php
 */
use Foo\Bar\Model\Baz;
use Foo\Bar\Model\BazFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\View\Result\PageFactory;

class Index implements ActionInterface
{
    // Create the related local class properties.
    private BazFactory $bazFactory;
    private PageFactory $pageFactory;
  
    // Add the Factory classes as arguments of the constructor...
    public function __construct(
        BazFactory $bazFactory,
        PageFactory $pageFactory
    ) {
        // ...and then assign them to the class properties.
        $this->bazFactory = $bazFactory;
        $this->pageFactory = $pageFactory;
    }
    
    public function execute()
    {
        /**
         * Within the function you would like your entity, call the create()
         * function on your class property. This returns an instance of that
         * model. Be sure to add the related typehint of the resulting object.
         */
        
        /** @var Baz **/
        $baz = $this->bazFactory->create();
        
        // This object can now call functions available on the model.
        $baz->myFunction();

        /*
         * The PageFactory also returns an instance of the Page model, which
         * shows a standard page to the user as a response to this controller.
         */

        /** @var Page **/
        $page = $this->pageFactory->create();
        
        return $page;
    }
}
Want to learn more?

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

M.academy logo