karolak/psr-container

PSR-11 container implementation.

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/karolak/psr-container

dev-master 2026-02-27 00:21 UTC

This package is auto-updated.

Last update: 2026-02-27 00:25:38 UTC


README

A minimal, zero-dependency PSR-11 container implementation for PHP.

All services are resolved lazily on first access and reused on subsequent calls.

Requirements

Installation

composer require karolak/psr-container

Usage

use Karolak\PsrContainer\Container;

$container = new Container([
    LoggerInterface::class => static fn (): FileLogger => new FileLogger('/var/log/app.log'),
    Connection::class      => static fn (): Connection => new Connection('sqlite::memory:'),
    UserRepository::class  => static function (Container $c): UserRepository {
        return new UserRepository(
            $c->get(Connection::class),
            $c->get(LoggerInterface::class),
        );
    },
]);

$repository = $container->get(UserRepository::class);

Each factory receives the container instance as its only argument, so you can resolve other services as dependencies. Every factory is called at most once — subsequent calls to get() return the cached instance.

OPcache optimization

For best performance, define your container factories in a dedicated PHP file. This allows OPcache to compile and cache the file, avoiding repeated parsing on every request.

// config/services.php
return [
    LoggerInterface::class => static fn (): FileLogger => new FileLogger('/var/log/app.log'),
    Connection::class      => static fn (): Connection => new Connection('sqlite::memory:'),
];
// public/index.php
$container = new Container(require __DIR__ . '/../config/services.php');

License

MIT