Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 42 ยท Requests and Output

Request, Response and Result Types

Read request parameters safely and return the right Magento result: page, JSON, raw, redirect or forward. Includes runnable stand-ins for each result type.

A controller action has two jobs: understand what the visitor asked for, and decide what to send back. Magento gives each job its own object. The request carries the input: the HTTP method, parameters, headers. The result describes the output: a page, a JSON document, a redirect. The action builds a result and returns it; the framework applies it to the response that goes to the browser.

This split matters because it keeps actions short and testable. An action never calls echo or header(). It reads from the request, makes a decision, and returns a result object. In this lesson you will read request data safely, meet the five result types, and run stand-ins for each. Real Magento classes are shown read-only; the stand-ins are plain PHP, so they are simpler than the real thing.

Reading the request

Inject Magento\Framework\App\RequestInterface and ask it for what you need:

PHP
<?php

namespace Acme\Hello\Controller\Greeting;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;

class Show implements HttpGetActionInterface
{
    public function __construct(
        private RequestInterface $request,
        private JsonFactory $jsonFactory
    ) {
    }

    public function execute(): ResultInterface
    {
        $id = (int) $this->request->getParam('id', 0);
        $result = $this->jsonFactory->create();

        return $result->setData(['id' => $id]);
    }
}

Useful request methods:

  • getParam($name, $default = null) returns one parameter. It looks at parameters from the URL path (/id/42) and the query string, and in a POST request at the form body too.
  • getParams() returns all of them as an array.
  • getPostValue() returns only form-body data, available on the HTTP request class used by web actions.
  • getMethod(), isPost() and isAjax() describe the request itself.
  • getHeader($name) reads a request header.

Remember that everything here is user input. Cast numbers ((int)), validate against allowed values, and escape anything you print. See Performance and Security for more, and Handling Forms for the plain PHP view of the same problem.

The five result types

You build results through ResultFactory constants or dedicated factories. Each one produces an object that knows how to put itself into the response.

Page

TYPE_PAGE (or Magento\Framework\View\Result\PageFactory) builds a full HTML page from layout XML, blocks and templates. You can set page details before returning it:

PHP
$page = $this->pageFactory->create();
$page->getConfig()->getTitle()->set(__('Welcome'));
return $page;

What the page contains is decided by layout files: Layout XML and Handles explains how, and Blocks, ViewModels and PHTML Templates covers the output.

JSON

TYPE_JSON (or JsonFactory) encodes data as JSON and sets the content type for you. It is the standard result for AJAX endpoints:

PHP
return $this->jsonFactory->create()->setData(['ok' => true, 'items' => $items]);

Raw

TYPE_RAW (or RawFactory) sends exactly the text you give it. Use it for tiny outputs such as plain text or a simple feed. You choose the content type with setHeader('Content-Type', 'text/plain').

Redirect

TYPE_REDIRECT (or RedirectFactory) sends the browser elsewhere. You pass a route path or a full URL:

PHP
return $this->redirectFactory->create()->setPath('customer/account');

The classic pattern is Post/Redirect/Get: after handling a form POST, redirect to a GET page, so a browser refresh does not submit the form again. Before redirecting, an action often adds a notice with the message manager (addSuccessMessage(), addErrorMessage()), which the next page displays.

Forward

TYPE_FORWARD hands the request to a different action inside the same request, without telling the browser. The URL stays the same:

PHP
$forward = $this->forwardFactory->create();
return $forward->setController('index')->forward('noroute');

Forwarding is how Magento shows its "404 not found" page for a URL that matched a route but not a valid thing. Redirect changes the URL and costs a second round trip; forward does not.

flowchart TD
    A["Action: execute()"] --> B{"What should the visitor get?"}
    B -->|"HTML page"| C["Page result<br/>layout + blocks"]
    B -->|"Data for JavaScript"| D["JSON result"]
    B -->|"Tiny text output"| E["Raw result"]
    B -->|"Go somewhere else"| F["Redirect result<br/>new URL"]
    B -->|"Reuse another action"| G["Forward result<br/>same URL"]
    C --> H["Response"]
    D --> H
    E --> H
    F --> H
    G --> H

An action returns exactly one result. The framework turns it into the response, or, for a forward, runs another action first.

Status codes and headers

Results can carry an HTTP status. On results derived from the framework's abstract result, such as JSON and raw, setHttpResponseCode(404) sets the status, and setHeader($name, $value) adds a header. An API-style action that fails validation should return a JSON body with a clear message and a 4xx status, not a successful 200 with an error hidden in the data. Redirects set their own 302 status; you rarely change it.

Try it: result objects and a response

This stand-in has a small Request, four result classes and a Response they write into. Real Magento classes are much bigger (cache headers, layout rendering, escaping rules), but the flow is the same: the action builds a result, then a render step turns it into status, headers and body.

PHP Actions returning results that render into a response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that 'abc' becomes 0 after the (int) cast, so the unknown-product branch handles it without any special code. That is the habit to copy: normalise input first, then decide.

Try it: forwarding and redirecting compared

Forward and redirect both end up showing a different action, but they behave differently for the browser. This stand-in makes the difference visible by counting round trips and showing the final URL.

PHP Forward versus redirect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The trace shows two browser requests for the redirect and just one for the forward: that extra trip is the price of a redirect, and the changed URL is what you gain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a Magento action return a result object instead of echoing output?

    Returning a result keeps output logic in the framework (headers, status, caching), and tests can inspect the returned object.
  2. 2. Which result keeps the URL in the browser unchanged while showing another action's content?

    Forward runs another action inside the same request. A redirect sends the browser to a new URL.
  3. 3. What should you do with a value read by getParam('id')?

    Request parameters come from the visitor. Cast numbers, validate against allowed values and escape on output.
  4. 4. What is the Post/Redirect/Get pattern for?

    After handling a POST, the action returns a redirect to a GET page. Refreshing that page then repeats only the GET.
  5. 5. Which result is the usual choice for an AJAX endpoint?

    The JSON result encodes data and sets the JSON content type, which is what JavaScript callers expect.

Summary

  • The request object carries input; a result object describes output; the framework applies it to the response.
  • Read input with RequestInterface::getParam() and friends, and treat all of it as untrusted.
  • The result types are page, JSON, raw, redirect and forward, built with ResultFactory or dedicated factories.
  • Redirect after a successful POST; use forward for in-request hand-offs such as the no-route page.
  • Return a proper 4xx status with an error body for failed API-style requests.

Next, find out how a page result gets its content in Layout XML and Handles.