*/ private array $factories = array(); /** * Resolved shared instances. * * @var array */ private array $instances = array(); /** * Register a service factory. * * @param string $id Service identifier. * @param Closure $factory Factory receiving this container, returning the service. */ public function set( string $id, Closure $factory ): void { $this->factories[ $id ] = $factory; unset( $this->instances[ $id ] ); } /** * Resolve a service, instantiating it on first access. * * @param string $id Service identifier. * @return mixed * @throws RuntimeException When the id was never registered. */ public function get( string $id ): mixed { if ( array_key_exists( $id, $this->instances ) ) { return $this->instances[ $id ]; } if ( ! isset( $this->factories[ $id ] ) ) { throw new RuntimeException( sprintf( 'Container: unknown service "%s".', esc_html( $id ) ) ); } $this->instances[ $id ] = ( $this->factories[ $id ] )( $this ); return $this->instances[ $id ]; } /** * Whether a service id is registered. * * @param string $id Service identifier. */ public function has( string $id ): bool { return isset( $this->factories[ $id ] ); } }