phpkernel / phpkernel
Lightweight, zero-dependency PHP 8.5 micro-framework with AOT-compiled routing and middleware
Requires
- php: >=8.5
- ext-json: *
- ext-mbstring: *
- ext-openssl: *
Requires (Dev)
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHPKernel is a lightweight, zero-dependency PHP 8.5 micro-framework built around ahead-of-time route compilation, strict typing, explicit layered context, and 100% unit test coverage.
Key Features
- PHP 8.5 Native: Built with strict typing (
declare(strict_types=1)), asymmetric property visibility (public private(set)), and modern syntax without legacy polyfills. - Ahead-of-Time Compiled Routing: Routes compile into static PHP maps (
patterns.php,map.php) for instant OPcache loading, zero runtime parsing, and automaticHEADsupport forGETroutes. - Ahead-of-Time Compiled Middleware: Global and route-specific middleware pipelines (
Rule::globalMiddleware(),->middleware()) are baked into compiled route maps at build time and executed as an onion pipeline with zero overhead on routes without middleware. - Layered Request Context: A predictable inheritance chain (
Encrypter ➔ Tool ➔ Response ➔ View) provides controllers with URL parsing, input merging, reverse routing, response builders, and template rendering in a single object without reflection-based DI overhead. - Custom Error Handling: Pass an optional error controller class to
Kernel(new Kernel($dir, ErrorController::class)) to render custom HTML or JSON error pages (403, 404, 500) with full access to the layered context and an automaticPlainfallback. - Security by Design:
- Sandboxed Filesystem (
SafeRoot): Lexical path validation preventing directory traversal (../), null-byte injection, and out-of-root access. - CSRF Protection: Built-in encrypted token generation and automatic
POSTvalidation inKernel. - Header & Output Safety: Strict CRLF header injection filtering in
Headers,EXTR_SKIPvariable isolation inBuffer, and automatic output buffer cleanup on template exceptions.
- Sandboxed Filesystem (
- Testing: 100% unit test coverage verified via PHPUnit 13.4.
Requirements
- PHP:
>= 8.5(withopenssl,json,mbstring) - Testing (Dev): PHPUnit
^13.4+ PCOV / Xdebug
Project Structure
├── application/
│ ├── rules.php # Route definitions
│ └── view/ # PHP templates
├── var/
│ ├── config/
│ │ ├── init.php # Compiled environment config & encoded key
│ │ └── key.bytes # Raw 32-byte encryption key
│ ├── log/ # UTC-stamped system logs
│ └── rules/ # Compiled routing tables (patterns, map)
├── src/
│ ├── Configuration/ # Cache builders (Install, Converter, Key)
│ ├── Foundation/ # Filesystem, SafeRoot, UtcClock
│ ├── Http/
│ │ ├── Procedure/ # Entry point (Kernel) and Encrypter
│ │ ├── Request/ # Rule, Path, and Internal (Compiler, Process, Url, Input)
│ │ └── Response/ # Plain, Blank, and Internal (Buffer, Emitter, Headers)
│ └── Process/ # Layered controller context (Tool -> Response -> View)
└── tests/ # PHPUnit 13.4 test suite (100% coverage)
Architecture Overview
1. Ahead-of-Time Route Compilation
Instead of parsing route definitions on every HTTP request, Install::compileRules() compiles application/rules.php into static PHP arrays inside var/rules/ (with automatic HEAD handling for GET routes):
patterns.php— compiles static and dynamic routes into an O(1) hash map and a(?|...)regex with pre-baked middleware chains forProcess::resolve().map.php— reverse-routing table indexed by route name and parameter count, used byTool::map()to generate validated URLs.
2. Layered Context Chain
Controllers extend PHPKernel\Process\View, gaining access to the full framework stack without container lookups:
PHPKernel\Http\Procedure\Encrypter # Symmetric key encryption/decryption
▲
PHPKernel\Process\Tool # Url, SafeRoot path(), reverse map(), CSRF, merged Input
▲
PHPKernel\Process\Response # htmlResponse(), jsonResponse(), plainResponse(), redirectResponse()
▲
PHPKernel\Process\View # Sandboxed renderTemplate() with Buffer
3. Isolated Template Rendering
View::renderTemplate() delegates rendering to PHPKernel\Http\Response\Internal\Buffer:
- Validates template paths through
SafeRootto prevent traversal outsideapplication/view/. - Extracts template variables using
EXTR_SKIPinside a closure to prevent variable collisions. - Passes a scoped
Toolinstance ($tool) to the template for URL generation and static asset paths without exposing response-sending methods to the view layer. - Wraps
requireintry/catchwithob_end_clean()so failed templates never leak partial output.
Usage Example
1. Define Routes (application/rules.php)
<?php
declare(strict_types=1);
use Application\Controller\UserController;
use PHPKernel\Http\Request\Rule;
Rule::route('/user/{id}', 'user.profile', UserController::class, ['GET'])
->where(['id' => '[0-9]+'])
->middleware(AuthMiddleware::class);
2. Create a Controller
<?php
declare(strict_types=1);
namespace Application\Controller;
use PHPKernel\Http\Request\Path;
use PHPKernel\Process\View;
final class UserController extends View
{
public function __invoke(Path $path): void
{
$this->renderTemplate('user/profile.php', [
'userId' => $path->int('id'),
]);
}
}
3. Render a Template (application/view/user/profile.php)
<?php
use PHPKernel\Process\Tool;
/** @var Tool $tool */
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Profile</title>
<link rel="stylesheet" href="<?= $tool->static('css/app.css') ?>">
</head>
<body>
<h1>User #<?= $userId ?></h1>
<a href="<?= $tool->map('user.profile', (string) $userId) ?>">Permalink</a>
</body>
</html>
4. Web Entry Point (public/index.php)
<?php
declare(strict_types=1);
use Application\Controller\ErrorController;
use PHPKernel\Http\Procedure\Kernel;
require dirname(__DIR__) . '/vendor/autoload.php';
new Kernel(dirname(__DIR__), ErrorController::class);
Running Tests
./vendor/bin/phpunit
To generate an HTML code coverage report (requires PCOV or Xdebug):
./vendor/bin/phpunit --coverage-html report
License
MIT License.