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
Requires
- php: >=8.4
- psr/container: ^2.0
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13
- vimeo/psalm: ^6.15
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
- PHP >= 8.4
- psr/container ^2.0
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