Return a standard page response

In a previous lesson, we learned how to create a basic controller for our module which simply terminates the PHP script execution and echos a string. While that was great for learning, in the real-world, we wouldn't really want to just stop execution in the middle of our application.

Instead, what we need to create a page response that fits in with Magento’s layout system. Magento has a class we can use which allows us to render a blank, empty page which we can then build on top of.

Inject the PageFactory object

First, we will define a private property in the constructor. Then, we’ll use dependency injection to inject the PageFactory object into the constructor. This class comes from Magento\\Framework\\View\\Result\\PageFactory. And last, we’ll assign it to a property named $pageFactory.

<?php

declare(strict_types=1);

namespace Macademy\\Jumpstart\\Controller\\Index;

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

class Index implements HttpGetActionInterface
{
    public function __construct(
        private PageFactory $pageFactory,
    ) {}

    public function execute()
    {
        die('Jumpstart!');
    }
}

Return a blank response from the PageFactory

A Factory is one of those special types of objects that is usually built and managed my Magento’s Object Manager. When we use factory classes to create objects, Object Manager will also provide a brand new instance of the object. This differs from the default functionality of having it always return an instance of the same object.

Factory objects are a bit unique compared to standard objects, because we need to call their create() method after they are instantiated to actually create a new instance of that object. We can return a new Page object in our execute function by calling this method directly:

public function execute()
{
    return $this->pageFactory->create();
}

Note that calling create() on factory objects always return an instance of the root object. This means that the return type defined on this execute method is actually a Page object, not an instance of the factory.

public function execute(): Page
{
    return $this->pageFactory->create();
}

Let’s go ahead and refresh our /jumpstart URL, and we should see an empty Magento page as a response. Since we didn’t get any errors, this tells us that our code is working properly.

Creating a standard blank page is an important step in Magento module development, since the response aligns perfectly with Magento's layout system. We can now start easily adding custom functionality and content to this empty page.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock