Magento 2: Return a standard page

YouTube player

Creating a Basic Page Response

Magento provides a class to render a blank page that we can build upon. Here’s how to create a basic page response in our index controller.

  1. Create the Constructor: Define the constructor and inject the necessary dependencies. We’ll use dependency injection to inject the PageFactory class.
namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;

use Magento\Framework\View\Result\PageFactory;

use Magento\Framework\App\Action\Context;

class Index extends Action

{

    public function __construct(

        private PageFactory $pageFactory,

    ) {}

    public function execute()

    {

        return $this->pageFactory->create();

    }

}
  1. Explanation:
    • Constructor: We define a private property $pageFactory and use dependency injection to inject PageFactory from Magento\Framework\View\Result.
    • Execute Method: The execute method returns an instance of the page created by the PageFactory.
    •  
  2. Factory Class: Factory classes in Magento are special objects managed by Magento’s object manager. They create new instances of objects each time the create method is called. This ensures that we get a new instance of the page object every time we request it.
  3. Testing: When we navigate to the front end of our site and refresh the page, we should see an empty Magento page. This confirms that our code is working properly.

Conclusion

Creating a standard blank page is an essential step in Magento module development. It ensures that the response aligns with Magento’s layout system, allowing us to easily add custom functionality and content.