Rasmus Lerdorf
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\Response\SapiEmitter;
use Zend\Diactoros\ServerRequestFactory;
$request = ServerRequestFactory::fromGlobals();
$response = new JsonResponse([
'greeting' => 'Hello ' . $request->getQueryParams()['name']
]);
(new SapiEmitter())->emit($response);
interface TodoServiceInterface
{
public function addTodo(int $id, string $title): void;
public function markTodoAsDone(int $id);
}
namespace Psr\Http\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
interface RequestHandlerInterface
{
public function handle(
ServerRequestInterface $request
): ResponseInterface;
}
AddTodo
final class AddTodo implements RequestHandlerInterface
{
private $todoService;
public function __construct(TodoServiceInterface $service)
{
$this->todoService = $todoService;
}
public function handle(ServerRequestInterface $request)
{
$data = $request->getParsedBody();
$this->todoService->addTodo(
$data['id'],
$data['title']
);
return new JsonResponse(['message' => 'Todo added']);
}
}
MarkTodoAsDone
final class MarkTodoAsDone implements RequestHandlerInterface
{
// ... Dependency Injection ... //
public function handle(ServerRequestInterface $request)
{
$data = $request->getParsedBody();
$this->todoService->markTodoAsDone($data['id']);
return new JsonResponse(['message' => 'Todo done']);
}
}
namespace Psr\Container;
interface ContainerInterface
{
public function get(string $id): mixed;
public function has(string $id): bool;
}
$ composer require psr/container
$container = new Container();
$handler = $container->get(AddTodo::class);
$request = ServerRequestFactory::fromGlobals();
$response = $handler->handle($request);
(new SapiEmitter())->emit($response);
namespace Psr\Http\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
interface MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface;
}
// Configure routes
$router = new Router($container);
$router->post('/todos', AddTodo::class);
$router->post('/todos/{id}/done', MarkTodoAsDone::class);
// Configure middleware pipeline
$pipeline = new MiddlewarePipeline($container);
$pipeline->pipe(ErrorHandler::class);
$pipeline->pipe(Authentication::class);
$pipeline->pipe($router);
$pipeline->pipe(Authorization::class);
$pipeline->pipe(InputValidation::class);
$pipeline->pipe(RequestHandler::class);
$request = ServerRequestFactory::fromGlobals();
$response = $pipeline->handle($request);
(new SapiEmitter())->emit($response);