Controllers

A controller is a PHP class created in Request scope. It receives dependencies through its constructor and may return a PSR-7 response directly.

Actions and dependencies

The container resolves ArticleController in the Request scope and injects a renderer and an application-owned ArticleRepository. The detail() argument id comes from the matching route segment. The controller passes the repository result to articles.detail; render() returns a PSR-7 response.

app/Controllers/ArticleController.php
<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Services\ArticleRepository;

use Lemonade\Framework\View\ViewRendererInterface;
use Psr\Http\Message\ResponseInterface;

final readonly class ArticleController
{
    public function __construct(
        private ViewRendererInterface $views,
        private ArticleRepository $articles,
    ) {}

    public function detail(string $id): ResponseInterface
    {
        return $this->views->render('articles.detail', [
            'article' => $this->articles->get($id),
        ]);
    }
}

Reading the request

An action can receive ServerRequestInterface or use the request-scoped RequestData service. Check the type of getParsedBody() for forms; RequestData::jsonPayload() reads a JSON object into an array.

Returning a response

HealthController injects Responses because show() returns JSON rather than an HTML view. json() creates a PSR-7 response with HTTP 200 by default and accepts a different status as its second argument. The same service also handles text and redirects.

Responses
<?php

declare(strict_types=1);

use Lemonade\Framework\Http\Response\Responses;
use Psr\Http\Message\ResponseInterface;

final readonly class HealthController
{
    public function __construct(private Responses $responses) {}

    public function show(): ResponseInterface
    {
        return $this->responses->json(['status' => 'ok']);
    }
}
Related documentationRead the Controllers and HTTP responses chapter in the documentation for more detail.

← All examples