Container.php
88 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Your\Namespace; |
| 4 | |
| 5 | use StellarWP\ContainerContract\ContainerInterface; |
| 6 | |
| 7 | // If you are including PHP-DI container using Strauss (recommended), then: |
| 8 | use Your\Namespace\DI\Container as PHPDIContainer; |
| 9 | |
| 10 | // If you are including the PHP-DI container directly, then you'd want to do: |
| 11 | //use DI\Container as PHPDIContainer; |
| 12 | |
| 13 | class Container implements ContainerInterface { |
| 14 | protected $container; |
| 15 | protected $singletons = []; |
| 16 | |
| 17 | /** |
| 18 | * Container constructor. |
| 19 | */ |
| 20 | public function __construct() { |
| 21 | $this->container = new PHPDIContainer(); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @inheritDoc |
| 26 | */ |
| 27 | public function bind( string $id, $implementation = null ) { |
| 28 | return $this->container->set( $id, $implementation ); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * @inheritDoc |
| 33 | */ |
| 34 | public function get( string $id ) { |
| 35 | return $this->container->get( $id ); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @inheritDoc |
| 40 | */ |
| 41 | public function has( string $id ) { |
| 42 | return $this->container->has( $id ); |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Build an entry of the container by its name. |
| 47 | * |
| 48 | * This method behave like get() except resolves the entry again every time. |
| 49 | * For example if the entry is a class then a new instance will be created each time. |
| 50 | * |
| 51 | * This method makes the container behave like a factory. |
| 52 | * |
| 53 | * @template T |
| 54 | * |
| 55 | * @param string|class-string<T> $name Entry name or a class name. |
| 56 | * @param array $parameters Optional parameters to use to build the entry. Use this to force |
| 57 | * specific parameters to specific values. Parameters not defined in this |
| 58 | * array will be resolved using the container. |
| 59 | * |
| 60 | * @return mixed|T |
| 61 | * @throws InvalidArgumentException The name parameter must be of type string. |
| 62 | * @throws DependencyException Error while resolving the entry. |
| 63 | * @throws NotFoundException No entry found for the given name. |
| 64 | */ |
| 65 | public function make( string $id, array $parameters = [] ) { |
| 66 | if ( ! empty( $this->singletons[ $id ] ) ) { |
| 67 | return $this->container->get( $id ); |
| 68 | } |
| 69 | |
| 70 | return $this->container->make( $id, $parameters ); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @inheritDoc |
| 75 | */ |
| 76 | public function singleton( string $id, $implementation = null ) { |
| 77 | $this->singletons[ $id ] = true; |
| 78 | return $this->container->set( $id, $implementation ); |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Defer all other calls to the container object. |
| 83 | */ |
| 84 | public function __call( $name, $args ) { |
| 85 | return $this->container->{$name}( ...$args ); |
| 86 | } |
| 87 | } |
| 88 |