Chapter 5 of 15
Controllers and HTTP responses.
A controller coordinates one HTTP use case and receives its dependencies through the constructor.
Controller classes
A controller can be an ordinary final class. The container resolves it in the Request scope, so it can inject request-scoped services. Keep only dispatchable actions public.
app/Controllers/ArticleController.php
<?php
declare(strict_types=1);
use Lemonade\Framework\View\ViewRendererInterface;
use Psr\Http\Message\ResponseInterface;
final readonly class ArticleController
{
public function __construct(private ViewRendererInterface $views) {}
public function detail(string $id): ResponseInterface
{
return $this->views->render('articles.detail', ['id' => $id]);
}
}Route parameters are passed as action arguments. ViewRendererInterface::render() returns a PSR-7 HTML response.
Response types
Use ViewRendererInterface for HTML views. Inject Responses for JSON, text, redirects, downloads, or streams.
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']);
}
}Responses::json() applies safe JSON encoding and accepts an HTTP status such as 201 or 422.