Magento 2
Controller Composition vs Inheritance
Free Preview
Composition (Magento 2.4+)
<?php
namespace Macademy\JsFun\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;

// Composition implements an action interface. Common interfaces to implement:
// Create - HttpPutActionInterface
// Read - HttpGetActionInterface
// Update - HttpPostActionInterface
// Delete - HttpDeleteActionInterface
class Index implements HttpGetActionInterface
{
    /** @var PageFactory */
    private $pageFactory;

    // Instantiating the Context object is no longer required
    public function __construct(
        PageFactory $pageFactory
    ) {
        // Calling parent::__construct() is also no longer needed
        $this->pageFactory = $pageFactory;
    }

    public function execute()
    {
        return $this->pageFactory->create();
    }
}
Inheritance (Magento 2.0-2.3, Deprecated)
<?php
namespace Foo\Bar\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;

// Controller action must extend (inherit) the Action class
class Index extends Action implements HttpGetActionInterface
{
    /** @var Context */
    private $context;

    /** @var PageFactory */
    private $pageFactory;

    // Not only must a Context object be created with dependency injection...
    public function __construct(
        Context $context,
        PageFactory $pageFactory
    ) {
        // ...but parent::__construct must be called with the $context object
        parent::__construct($context);
        $this->pageFactory = $pageFactory;
    }

    public function execute()
    {
        return $this->pageFactory->create();
    }
}
Want to learn more?

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

M.academy logo