withinboredom / building-blocks
v0.2.4
2022-11-21 10:23 UTC
Requires
- php: >=8.1
- withinboredom/response-code: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.5
README
这是一个完全忽略PSR的库,专注于简洁。它不是一个用于构建复杂应用的库,而是在你需要以最少的麻烦完成事情时。
将错误转换为异常
ErrorControl
类允许轻松地将错误转换为异常
<?php 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; } };
Cache-Control
缓存对浏览器来说是非常重要的信息,可以为您节省大量的带宽。
$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
一个极其简单的路由器
一个在O(routes + parameters)时间内工作的非常简单的路由器。
$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();