Search by

phpkernel / phpkernel

phpkernel

Lightweight, zero-dependency PHP 8.5 micro-framework with AOT-compiled routing and middleware

Package info

codeberg.org/phpkernel/phpkernel

Issues

pkg:composer/phpkernel/phpkernel

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

v1.5.1 2026-11-15 19:15 UTC

This package is auto-updated.

Last update: 2026-11-15 16:49:46 UTC


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 automatic HEAD support for GET routes.
  • 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 automatic Plain fallback.
  • 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 POST validation in Kernel.
    • Header & Output Safety: Strict CRLF header injection filtering in Headers, EXTR_SKIP variable isolation in Buffer, and automatic output buffer cleanup on template exceptions.
  • Testing: 100% unit test coverage verified via PHPUnit 13.4.

Requirements

  • PHP: >= 8.5 (with openssl, 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 for Process::resolve().
  • map.php — reverse-routing table indexed by route name and parameter count, used by Tool::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 SafeRoot to prevent traversal outside application/view/.
  • Extracts template variables using EXTR_SKIP inside a closure to prevent variable collisions.
  • Passes a scoped Tool instance ($tool) to the template for URL generation and static asset paths without exposing response-sending methods to the view layer.
  • Wraps require in try/catch with ob_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.