netolabs / simple-container
Extremely basic and fast implementation of PSR-11
Installs: 2 041
Dependents: 2
Suggesters: 0
Security: 0
Stars: 3
Watchers: 4
Forks: 1
Open Issues: 0
Requires
- php: >=7.3
- psr/container: ^1.0
Requires (Dev)
- phake/phake: ^3.1
- phpmd/phpmd: 2.8.*
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: ^3.5
Provides
README
Extremely basic and fast implementation of the PSR-11 container standard. It's not intended to do fancy dependency injection, just the absolute bare minimum. Consider using PHP-DI or Symfony DI for a more complete implementation.
Install
Via Composer
$ composer require netolabs/simple-container
Requirements
PHP version 7.3 and up is required.
Usage
Adding a definition to the container
$container = new SimpleContainer(); $service = new MySuperCoolService(); $container->set(MySuperCoolService::class, $service);
Fetching from the container
if ($container->has(MySuperCoolService::class) { $service = $container->get(MySuperCoolService::class); }
Adding a callable definition
Here we are adding an anonymous function which will be invoked the first time the definition is accessed via set()
.
The computed value will be cached for subsequent accesses.
$container = new SimpleContainer(); $container->set('myCallable', function() { return 'a computed value'; }); $value = $container->get('myCallable'); // value is 'a computed value'
Invoking the callable for every access
If you require the callable to be invoked every time you access the definition, you can use the resolve()
method instead.
$value = $container->resolve('myCallable'); // value is 'a computed value'
License
The MIT License (MIT). Please see the License File for more information.