PHP code example of georgeff / kernel

1. Go to this page and download the library: Download georgeff/kernel 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/ */

    

georgeff / kernel example snippets


use Georgeff\Kernel\Environment\Production;
use Georgeff\Kernel\Kernel;

$kernel = new Kernel(new Production());

$kernel->define('logger', fn() => new FileLogger('/var/log/app.log'))->share();
$kernel->define('mailer', fn() => new SmtpMailer('localhost'));

$kernel->boot();

$container = $kernel->getContainer();
$logger = $container->get('logger');

use Georgeff\Kernel\Environment\Local;
use Georgeff\Kernel\Kernel;

$kernel = new Kernel(new Local(), debug: true);

$kernel->getEnvironment()->getValue(); // 'local'
$kernel->getEnvironment()->is('local'); // true
$kernel->isDebug();                     // true

use Georgeff\Kernel\Environment\AbstractEnvironment;

final class Canary extends AbstractEnvironment
{
    public function getValue(): string
    {
        return 'canary';
    }
}

use Georgeff\Kernel\Support\EnvironmentResolver;
use Georgeff\Kernel\Support\Env;

$resolver = new EnvironmentResolver();
$resolver->register('canary', Canary::class);

$kernel = new Kernel($resolver->resolve(Env::get('APP_ENV', 'production')));

$kernel->define('db.connection', fn() => new PdoConnection($dsn, $user, $pass))
    ->share()
    ->alias(ConnectionInterface::class)
    ->tag('db.connections');

$kernel->defineFallback('db.connection', fn() => new PdoConnection('sqlite::memory:'))->share();

// Some other module (or the application itself) defines the real thing:
$kernel->define('db.connection', fn() => new PdoConnection($dsn, $user, $pass))->share();

$kernel->boot();
// The real definition wins — the fallback is never used, regardless of which was registered first.

$kernel->defineFallback('db.connection', fn() => new PdoConnection('sqlite::memory:'))->share();

$kernel->boot();
// PdoConnection('sqlite::memory:') — nothing else claimed 'db.connection'.

$kernel->define(FirstMiddleware::class, fn() => new FirstMiddleware())->tag('http.middleware');
$kernel->define(SecondMiddleware::class, fn() => new SecondMiddleware())->tag('http.middleware');

use Georgeff\Kernel\DI\TagRegistryInterface;

$kernel->boot();

$registry   = $kernel->getContainer()->get(TagRegistryInterface::class);
$middleware = $registry->getTagged('http.middleware');
// [FirstMiddleware, SecondMiddleware] — resolved in registration order

$kernel->define(LoggerInterface::class, fn() => new FileLogger('/var/log/app.log'))->share();

$kernel->decorate(
    LoggerInterface::class,
    fn(LoggerInterface $inner, ContainerInterface $c) => new TimestampLogger($inner),
);

$kernel->boot();

$logger = $kernel->getContainer()->get(LoggerInterface::class);
// TimestampLogger wrapping FileLogger

final class LoggingModule implements ModuleInterface
{
    public function register(KernelInterface $kernel): void
    {
        $kernel->decorate(
            CacheInterface::class,
            fn(CacheInterface $inner, ContainerInterface $c) => new LoggingCache(
                $inner,
                $c->get(LoggerInterface::class),
            ),
        );
    }
}

$kernel->define(QueueInterface::class, fn() => new RabbitMQQueue($config))->share();

$kernel->override(QueueInterface::class, fn() => new InMemoryQueue());

$kernel->boot();

$queue = $kernel->getContainer()->get(QueueInterface::class);
// InMemoryQueue

$kernel->override(QueueInterface::class, fn() => new InMemoryQueue());

$kernel->addModule(new QueueModule()); // registers the real QueueInterface

$kernel->boot();
// InMemoryQueue wins - the override is applied after QueueModule::register() runs

$kernel->override(QueueInterface::class, fn() => new InMemoryQueue())->share();

$kernel->override(QueueInterface::class, fn() => new InMemoryQueue(), preserve: true);
// InMemoryQueue is shared, aliased, and tagged exactly like the original QueueInterface registration

use Georgeff\Kernel\KernelInterface;
use Georgeff\Kernel\Contract\ModuleInterface;

final class DatabaseModule implements ModuleInterface
{
    public function register(KernelInterface $kernel): void
    {
        $kernel->define('db.connection', fn() => new PdoConnection(getenv('DB_DSN')))
            ->share()
            ->alias(ConnectionInterface::class);
    }
}

use Georgeff\Kernel\Config\ConfigInterface;
use Georgeff\Kernel\Contract\ConfigurableModuleInterface;
use Georgeff\Kernel\Contract\EnvironmentInterface;
use Georgeff\Kernel\KernelInterface;

final class DatabaseModule implements ConfigurableModuleInterface
{
    public function register(KernelInterface $kernel): void
    {
        $kernel->define('db.connection', fn(ContainerInterface $c) => new PdoConnection(
            $c->get(ConfigInterface::class)->branch('db')->get('dsn'),
        ))->share();
    }

    public function config(EnvironmentInterface $env): array
    {
        return [
            'db' => [
                'dsn'  => getenv('DB_DSN') ?: 'sqlite::memory:',
                'host' => getenv('DB_HOST') ?: 'localhost',
            ],
        ];
    }
}

public function config(EnvironmentInterface $env): array
{
    return [
        'db' => [
            'dsn' => $env->is('testing') ? 'sqlite::memory:' : getenv('DB_DSN'),
        ],
    ];
}

use Georgeff\Kernel\Support\Env;

public function config(EnvironmentInterface $env): array
{
    return [
        'db' => [
            'dsn'  => Env::get('DB_DSN', 'sqlite::memory:'),
            'port' => Env::get('DB_PORT', '3306'),
            'log'  => Env::get('DB_LOG', false),
        ],
    ];
}

use Georgeff\Kernel\Config\ConfigInterface;

$config = $kernel->getContainer()->get(ConfigInterface::class);

$config->has('db');                    // true
$config->branch('db')->get('port');    // 5432
$config->branch('missing')->isEmpty(); // true — a missing key produces an empty (not null) branch
$config->all();                        // the full merged config as a plain array

use Georgeff\Kernel\KernelInterface;
use Georgeff\Kernel\Contract\BootableModuleInterface;
use Psr\Container\ContainerInterface;

final class MigrationModule implements BootableModuleInterface
{
    public function register(KernelInterface $kernel): void { /* ... */ }

    public function boot(ContainerInterface $container): void
    {
        $container->get(Migrator::class)->run();
    }
}

$kernel = new Kernel(new Production());

$kernel
    ->addModule(new DatabaseModule())
    ->addModule(new CacheModule())
    ->addModule(new MigrationModule());

$kernel->boot();

$kernel->addModule(new DatabaseModule());

$kernel->getModules(); // [DatabaseModule::class]

use Georgeff\Kernel\Contract\AggregateModuleInterface;
use Georgeff\Kernel\Contract\EnvironmentInterface;
use Georgeff\Kernel\Contract\ModuleInterface;
use Georgeff\Kernel\KernelInterface;

final class DatabaseModule implements AggregateModuleInterface
{
    public function register(KernelInterface $kernel): void
    {
        // register this module's own services, if any
    }

    public function modules(EnvironmentInterface $env): array
    {
        $modules = [new MigrationModule()];

        if (!$env->is('production')) {
            $modules[] = new DatabaseDebugModule();
        }

        return $modules;
    }
}

$kernel->addModule(new DatabaseModule());
// MigrationModule (and DatabaseDebugModule outside production) are loaded automatically.

$kernel->onBooting(function (KernelInterface $kernel) {
    $kernel->define('dynamic', fn() => new SomeService());
});

$kernel->onBooted(function (KernelInterface $kernel) {
    $kernel->getContainer()->get('logger')->info('Kernel booted');
});

$kernel->onShutdown(function (KernelInterface $kernel) {
    // isShutdown() is still false here
});

$kernel->afterShutdown(function (KernelInterface $kernel) {
    // isShutdown() is true here
});

$kernel->onResolving(function (string $id) {
    // about to resolve $id
});

$kernel->onResolved(function (string $id, mixed $resolved) {
    // $id was just resolved to $resolved via its factory
});

$kernel->boot();

// handle a request, run a command, etc.

$kernel->shutdown();

$kernel->isShutdown(); // true

$kernel = new Kernel(new Production());
$kernel->enableGc();
$kernel->boot();

final class SomeModule implements ModuleInterface
{
    public function register(KernelInterface $kernel): void
    {
        $kernel->enableGc();
    }
}

use Georgeff\Kernel\Contract\ResettableInterface;

final class ConnectionPool implements ResettableInterface
{
    public function reset(): void
    {
        // clear internal state
    }
}

$kernel->define(ConnectionPool::class, fn() => new ConnectionPool())->share();
$kernel->boot();

$kernel->getContainer()->get(ConnectionPool::class);

$kernel->resetShared();
// ConnectionPool::reset() was called automatically — no manual tagging 

$kernel->resetShared(failureThreshold: 5);

use Georgeff\Kernel\Contract\ThresholdAwareResettableInterface;

final class FlakyCache implements ThresholdAwareResettableInterface
{
    public function reset(): void { /* ... */ }

    public function getFailureThreshold(): int
    {
        return 1; // give up after the very first failure
    }
}

$kernel->define(ConnectionPool::class, fn() => new ConnectionPool())->share()->tag('db');
$kernel->define(SessionCache::class, fn() => new SessionCache())->share()->tag('cache');

$kernel->boot();
$kernel->getContainer()->get(ConnectionPool::class);
$kernel->getContainer()->get(SessionCache::class);

$kernel->resetShared(3, 'db');
// Only ConnectionPool::reset() was called — SessionCache is untouched.

$kernel->resetShared(3, 'db', 'cache');
// Both are reset — a service tagged with more than one requested tag is still only reset once.

$builder = new MyContainerBuilder();
$kernel = new Kernel(new Production(), $builder);

$kernel = new Kernel(new Development(), debug: true);
$kernel->boot();

$kernel->getStartTime(); // float (microtime)
$kernel->getDebugInfo(); // profiles + components (module/service-resolution/resetter data), merged by Profiler\Profiler

use Georgeff\Kernel\Contract\DebuggableInterface;

final class ConnectionPool implements DebuggableInterface
{
    public function getDebugInfo(): array
    {
        return ['active' => $this->activeCount, 'idle' => $this->idleCount];
    }
}

use Georgeff\Kernel\Exception\KernelExceptionInterface;

try {
    $kernel->boot();
} catch (KernelExceptionInterface $e) {
    // KernelException, ModuleException, ConfigException, DefinitionException,
    // EnvironmentException, HookException, or ServiceResetException
}

use Georgeff\Kernel\Exception\KernelException;

// Always throws
KernelException::throw('Something went wrong');

// Throws if $condition is true
KernelException::throwIf($this->isBooted(), 'Kernel is already booted');

// Throws if $condition is false
KernelException::throwIfNot($this->isBooted(), 'Kernel has not been booted');

use Georgeff\Kernel\Contract\RunnableKernelInterface;

class ConsoleKernel extends Kernel implements RunnableKernelInterface
{
    public function run(): int
    {
        $this->boot();

        // dispatch console command...

        return 0;
    }
}