Guide

Controllers & Responses

What `AbstractController` provides and when a shared application layer is useful.

Framework base: AbstractController

The framework provides AbstractController with helpers for requests, responses, and services, including view(), url(), validator(), flash(), filesystem(), upload(), translator(), and breadcrumb().

example.php
<?php

declare(strict_types=1);

namespace App\Controllers;

use Lemonade\Framework\Core\AbstractController;
use Psr\Http\Message\ResponseInterface;

final class ArticleController extends AbstractController
{
    public function detail(int $id): ResponseInterface
    {
        return $this->json([
            'id' => $id,
            'expects_json' => $this->expectsJson(),
        ]);
    }
}

A shared application controller

The application can optionally add AppController extends AbstractController. It is useful for shared rendering, common data, metadata, breadcrumbs, or small helpers. It is not a framework requirement.

example.php
<?php

declare(strict_types=1);

namespace App\Controllers;

use Lemonade\Framework\Core\AbstractController;
use Psr\Http\Message\ResponseInterface;

abstract class AppController extends AbstractController
{
    /**
     * @param array<string, mixed> $data
     */
    protected function page(string $view, array $data = [], int $status = 200): ResponseInterface
    {
        return $this->html(
            $this->view()->template(
                'layouts.app',
                $view,
                $data,
            ),
            $status,
        );
    }
}

Additional layers in larger applications

A larger application can add more layers on top of AppController for the public site, administration, locale handling, or canonical redirects. That is an application design choice, not a required framework hierarchy.

example.php
AbstractController
    ↓
Optional application base controller
    ↓
Optional specialized controller
    ↓
Concrete controller

Plain PSR controllers are valid too

A controller does not have to extend AbstractController if you prefer to build PSR responses directly with ResponseFactoryInterface and StreamFactoryInterface.

example.php
<?php

declare(strict_types=1);

namespace App\Controllers;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;

final class StatusController
{
    public function __construct(
        private readonly ResponseFactoryInterface $responses,
        private readonly StreamFactoryInterface $streams,
    ) {}

    public function index(): ResponseInterface
    {
        return $this->responses
            ->createResponse(200)
            ->withHeader('Content-Type', 'text/html; charset=UTF-8')
            ->withBody($this->streams->createStream('<h1>Status OK</h1>'));
    }
}