PHP code example of withinboredom / building-blocks

1. Go to this page and download the library: Download withinboredom/building-blocks library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

withinboredom / building-blocks example snippets




new class extends ErrorControl {
    protected function handleUnhandledException(Throwable $exception): void
    {
        $message = [
            'exception_type' => get_class($exception),
            'post' => file_get_contents('php://input'),
            'url' => $_SERVER['REQUEST_URI'],
            'ip' => $_SERVER['REMOTE_ADDR'],
            'message' => $exception->getMessage(),
            'line' => $exception->getLine(),
            'file' => $exception->getFile(),
            'trace' => $exception->getTraceAsString(),
            'num' => $exception->getCode(),
        ];
        error_log(json_encode($message, JSON_PRETTY_PRINT), 4);
        if (!headers_sent()) {
            http_response_code(HttpResponseCode::InternalServerError);
            die();
        }
    }

    protected function getIgnoredErrorLevel(): int
    {
        return E_DEPRECATED;
    }
};

$cacheHeaders = new ResponseCacheControl(
    static fn() => $_SERVER['HTTP_IF_NONE_MATCH'] ?? '',
    static fn() => new DateTimeImmutable($_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? 'this minute')
);
if(($status = $cacheHeaders->recommendStatus($etag, $expiresAt)) !== null) {
    http_response_code($status->value);
    die();
}
$headers = $cacheHeaders->addTerm(CacheResponseTerms::Immutable)->recommendStatus($etag, $expiresAt);
// pass headers to PSR response object

$router = new Router($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
$router->addRoute('/', static fn() => new Result(\Withinboredom\ResponseCode\HttpResponseCode::Ok, 'Hello, world!'));
$router->addRoute('/hello/:name', static fn(string $name) => new Result(\Withinboredom\ResponseCode\HttpResponseCode::Ok, "Hello, $name!"));

// emit the result of the routing and die
$router->doRouting()->emit();