ntentan / panie
A thin DI container for NtentanFX
Installs: 3 729
Dependents: 8
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 2
Requires
- php: >=7.1
- psr/container: ^1.0
Requires (Dev)
- phpunit/phpunit: @stable
README
A PSR-Container compatible dependency injection container built for use in the ntentan framework. However, just like the other components in the framework, ntentan is not required for panie to work. Panie can be used as a dependency injection container in its own right.
Usage
To create an instance of the container we use:
<?php require "vendor/autoload.php"; $container = new ntentan\panie\Container(); $fooInstance = $container->resolve(Foo::class);
Panie will create an instance of the Foo
class and autowire the type hinted dependencies if our Foo
class is defined as follows:
<?php class Foo { private $bar; public function __constructor(Bar $bar) { $this->bar = $bar; } }
Configuring
In cases where we want to provide specific wiring, we can configure the container by providing with options to use when resolving class types.
As a example, in the case where our Foo
class takes a BarInterface
iterface and we specifically want the BarImplementation
class, we can wire the container as follows:
<?php require "vendor/autoload.php"; $container = new ntentan\panie\Container(); $container->bind(BarInterface::class)->to(BarImplementation::class); $fooInstance = $container->get(Foo::class);
The container can also take a factory function that returns an instance of the required types.
<?php require "vendor/autoload.php"; $container = new ntentan\panie\Container(); $container->bind(BarInterface::class)->to(function(){ return new BarImplementation(); });
You can also make the container maintain an internal singleton of a particular service by specifying the singleton flag when binding types.
<?php require "vendor/autoload.php"; $container = new ntentan\panie\Container(); $container->bind(BarInterface::class)->to(BarImplementation::class)->asSingleton(); $fooInstance = $container->get(Foo::class);
Apart from the bind
and to
functions, the container has a setup
function that takes an associative array with wiring info for the container. In this case, a possible wiring could be ...
$container->setup([ BarInterface::class => BarImplementation::class ]);
... or for singletons and factories ...
$container->setup([ BarInterface::class => [function(){ ... }, 'singleton' => true] ]);