*/ private array $factories = array(); /** * Resolved singletons keyed by service id. * * @var array */ private array $instances = array(); /** * Register a shared service factory. * * @param string $id Service id (interface or class name). * @param callable $factory Factory receiving the container. */ public function share( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; } /** * Whether a service id is known. * * @param string $id Service id. */ public function has( string $id ): bool { return isset( $this->factories[ $id ] ) || isset( $this->instances[ $id ] ); } /** * Resolve a service. * * @param string $id Service id. * @return mixed * @throws InvalidArgumentException When the id is unknown. */ public function get( string $id ): mixed { if ( isset( $this->instances[ $id ] ) ) { return $this->instances[ $id ]; } if ( ! isset( $this->factories[ $id ] ) ) { throw new InvalidArgumentException( esc_html( "Unknown service: {$id}" ) ); } $this->instances[ $id ] = ( $this->factories[ $id ] )( $this ); return $this->instances[ $id ]; } }