Last active 1729621598

An example of how you can write a simple one script framework for a website using PSR-15.

composer.json Raw
1{
2 "require": {
3 "laminas/laminas-stratigility": "^3.2",
4 "mezzio/mezzio-fastroute": "^3.0",
5 "laminas/laminas-diactoros": "^2.3",
6 "laminas/laminas-httphandlerrunner": "^1.2"
7 }
8}
index.php Raw
1<?php
2
3use FastRoute\RouteCollector;
4use Laminas\Diactoros\ResponseFactory;
5use Laminas\Diactoros\ServerRequestFactory;
6use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
7use Laminas\HttpHandlerRunner\RequestHandlerRunner;
8use Laminas\Stratigility\Middleware\ErrorHandler;
9use Laminas\Stratigility\MiddlewarePipe;
10use Mezzio\Router\FastRouteRouter;
11use Mezzio\Router\Middleware\DispatchMiddleware;
12use Mezzio\Router\Middleware\RouteMiddleware;
13use Psr\Http\Message\ResponseFactoryInterface;
14use Psr\Http\Message\ResponseInterface;
15use Psr\Http\Message\ServerRequestInterface;
16use Psr\Http\Server\RequestHandlerInterface;
17
18require './vendor/autoload.php';
19
20$responseFactory = new ResponseFactory();
21$router = new FastRouteRouter();
22$routes = new RouteCollector($router);
23$app = new MiddlewarePipe();
24
25$app->pipe(new ErrorHandler([$responseFactory, 'createResponse']));
26$app->pipe(new RouteMiddleware($router));
27$app->pipe(new DispatchMiddleware());
28
29$routes->get('/hello', new class ($responseFactory) implements RequestHandlerInterface {
30 /** @var ResponseFactoryInterface */
31 private $responseFactory;
32
33 public function __construct(ResponseFactoryInterface $responseFactory)
34 {
35 $this->responseFactory = $responseFactory;
36 }
37
38 public function handle(ServerRequestInterface $request): ResponseInterface
39 {
40 $response = $this->responseFactory->createResponse();
41 $response->getBody()->write('Hello world');
42 return $response;
43 }
44});
45
46$runner = new RequestHandlerRunner(
47 $app,
48 new SapiEmitter(),
49 [ServerRequestFactory::class, 'fromGlobals'],
50 function (Throwable $error) use ($responseFactory): ResponseInterface {
51 $response = $responseFactory->createResponse(500)
52 ->withHeader('Content-Type', 'application/json');
53 $response->getBody()->write(json_encode([
54 'error' => $error->getMessage(),
55 'trace' => $error->getTrace(),
56 ]));
57 return $response;
58 }
59);
60$runner->run();