*/ private $factories = array(); /** @var array */ private $instances = array(); /** * Register a shared service factory. * * @param string $id Service id. * @param callable $factory Factory receiving the container. */ public function set( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; unset( $this->instances[ $id ] ); } /** * Resolve a service. * * @param string $id Service id. * @return mixed * @throws \RuntimeException When the service is unknown. */ public function get( string $id ) { if ( array_key_exists( $id, $this->instances ) ) { return $this->instances[ $id ]; } if ( ! isset( $this->factories[ $id ] ) ) { throw new \RuntimeException( 'Unknown service: ' . esc_html( $id ) ); } $this->instances[ $id ] = call_user_func( $this->factories[ $id ], $this ); return $this->instances[ $id ]; } /** * Whether a service is registered. * * @param string $id Service id. */ public function has( string $id ): bool { return isset( $this->factories[ $id ] ); } }