wiznetic/kernel

Programmable lifecycle microkernel by Wiznetic

Maintainers

Package info

github.com/wiznetic-git/kernel

pkg:composer/wiznetic/kernel

Statistics

Installs: 22

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v2.0.0 2026-04-18 23:06 UTC

This package is auto-updated.

Last update: 2026-04-18 23:08:23 UTC


README

Programmable lifecycle microkernel. Без MVC, без routing, без controller — само execution engine с пълен контрол.

Инсталация

composer require wiznetic/kernel

Идентичност

Пакет wiznetic/kernel
Namespace Wiznetic\Kernel
Версия 2.0.0
Лиценз MIT

Файлова структура

src/
  Kernel.php   — lifecycle engine + dispatch
  Listing.php  — influence chaining върху listener
  Event.php    — базов клас за custom events
  Trace.php    — execution recorder

Lifecycle

Kernel::handle() изпълнява фиксирана последователност от стъпки:

before:request  →  on:request  →  after:request
before:process  →  on:process  →  after:process
before:response →  on:response →  after:response

Всеки callback получава $ctx:

$ctx->request   // входящият request
$ctx->response  // изходящият response
$ctx->data      // споделени данни между hooks
$ctx->events    // dispatched events, indexed by class

API

Standalone lifecycle hooks

Kernel::before('process', function($ctx) { /* auth */ });
Kernel::on('process',     function($ctx) { $ctx->response = '...'; });
Kernel::after('response', function($ctx) { /* log */ });

Kernel::handle($request);

Custom events — dispatch

use Wiznetic\Kernel\Event;

class UserCreated extends Event {
    public function __construct(public readonly array $user) {}
}

// Регистрирай listener
Kernel::listen(UserCreated::class, UserCreatedHandler::class);

// Dispatch
Kernel::dispatch(new UserCreated(['id' => 1, 'name' => 'John']));

Handler класът имплементира handle():

class UserCreatedHandler {
    public function handle(UserCreated $event): void {
        // $event->user
    }
}

Спиране на propagation:

class UserCreatedHandler {
    public function handle(UserCreated $event): void {
        $event->stopPropagation(); // следващите handlers не се изпълняват
    }
}

Listing — influence методи

Kernel::listen() връща Listing обект. Чрез него позиционираш listener-а в lifecycle-а — кога точно да се изпълни и какво да получи.

Kernel::listen(UserCreated::class, UserCreatedHandler::class)
    ->before('request', 'ctx')    // изпълни преди request, подай $ctx
    ->after('request',  'event')  // изпълни след request, подай event обекта
    ->on('process',     'all');   // изпълни при process, подай и двете

Един и същи handler клас — различни данни — различни точки от процеса.

Payload selector

Стойност Handler получава
'ctx' $ctx (lifecycle контекст)
'event' Event обекта (или null ако не е dispatch-нат)
'all' $ctx, $event (default)
callable ти решаваш
// Custom payload — callable
Kernel::listen(UserCreated::class, UserCreatedHandler::class)
    ->before('process', fn($ctx, $event) => [$ctx->request, $event?->user]);

Handler-ът при influence получава точно това, което си декларирал:

class UserCreatedHandler {
    // когато receive = 'ctx'
    public function handle(object $ctx): void {}

    // когато receive = 'event'
    public function handle(?UserCreated $event): void {}

    // когато receive = 'all'
    public function handle(object $ctx, ?UserCreated $event): void {}
}

Trace

Проследява всяко изпълнение — lifecycle hook, dispatch, influence.

Kernel::trace(true);   // включи
Kernel::handle($req);

$log = Kernel::getTrace();
// [
//   ['phase' => 'before', 'step' => 'request',  'handler' => 'closure',            'duration' => 0.12],
//   ['phase' => 'dispatch', 'step' => 'UserCreated', 'handler' => 'UserCreatedHandler', 'duration' => 1.03],
//   ['phase' => 'on',     'step' => 'process',  'handler' => 'UserCreatedHandler', 'duration' => 0.44],
// ]

Kernel::trace(false);  // изключи
Trace::clear();        // изчисти лога

Всеки запис:

Поле Описание
phase before / on / after / dispatch / influence
step lifecycle стъпка или event class
handler клас или closure
duration ms
at microtime(true) timestamp

Пълен пример

use Wiznetic\Kernel\Kernel;
use Wiznetic\Kernel\Event;

// Custom event
class OrderPlaced extends Event {
    public function __construct(public readonly int $orderId) {}
}

// Handler
class OrderHandler {
    public function handle(object $ctx, ?OrderPlaced $event): void {
        // достъп и до lifecycle ctx и до event-а
    }
}

// Регистрация
Kernel::listen(OrderPlaced::class, OrderHandler::class)
    ->before('process', 'ctx')           // преди process — само ctx
    ->after('process',  'all')           // след process — ctx + event
    ->on('response',    fn($ctx, $e) => [$e?->orderId]); // само orderId

// Standalone hook
Kernel::before('request', function($ctx) {
    $ctx->data['start'] = microtime(true);
});

// Trace
Kernel::trace(true);

// Dispatch и стартиране
Kernel::dispatch(new OrderPlaced(42));
Kernel::handle($_SERVER);

dump(Kernel::getTrace());

Архитектурни принципи

  • Kernel не знае за MVC, routing, controller, view
  • Lifecycle е отворен — всяка стъпка е hooк-ваща
  • Един handler може да участва на множество lifecycle точки с различни данни
  • Trace е opt-in — нулев overhead когато е изключен
  • PSR-4 autoload, без външни зависимости