Controllery a odpovědi
Co nabízí `AbstractController` a kdy se vyplatí přidat společnou aplikační vrstvu.
Základ frameworku: AbstractController
Framework poskytuje AbstractController s helpery pro práci s requestem, response a službami, například view(), url(), validator(), flash(), filesystem(), upload(), translator() a 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(),
]);
}
}Společný aplikační controller
Aplikace může volitelně přidat AppController extends AbstractController. Hodí se pro společné renderování, sdílená data, metadata, breadcrumbs nebo drobné helpery. Není to požadavek frameworku.
<?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,
);
}
}Další vrstvy ve větších aplikacích
Ve větší aplikaci můžeš nad AppController přidat další vrstvy pro veřejný web, administraci, práci s locale nebo canonical redirecty. Je to rozhodnutí aplikace, ne povinná hierarchie frameworku.
AbstractController
↓
Optional application base controller
↓
Optional specialized controller
↓
Concrete controllerPoužít můžeš i čistý PSR controller
Controller nemusí dědit z AbstractController, pokud ti víc vyhovuje skládat PSR response přímo přes ResponseFactoryInterface a 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>'));
}
}