Controller e response
Cosa offre `AbstractController` e quando conviene aggiungere uno strato applicativo condiviso.
Base del framework: AbstractController
Il framework fornisce AbstractController con helper per request, response e servizi, tra cui view(), url(), validator(), flash(), filesystem(), upload(), translator() e breadcrumb().
<?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(),
]);
}
}Controller applicativo condiviso
L’applicazione può aggiungere facoltativamente AppController extends AbstractController. È utile per rendering condiviso, dati comuni, metadata, breadcrumbs o piccoli helper. Non è un requisito del framework.
<?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,
);
}
}Strati aggiuntivi nelle applicazioni più grandi
In un’applicazione più ampia puoi aggiungere altri strati sopra AppController per il sito pubblico, l’amministrazione, la gestione del locale o i canonical redirect. È una scelta architetturale dell’applicazione, non una gerarchia obbligatoria del framework.
AbstractController
↓
Optional application base controller
↓
Optional specialized controller
↓
Concrete controllerSono validi anche controller PSR puri
Un controller non deve necessariamente estendere AbstractController se preferisci costruire direttamente le response PSR con ResponseFactoryInterface e StreamFactoryInterface.
<?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>'));
}
}