*/ private array $factories = array(); /** * Built services, keyed by class name. * * @var array */ private array $instances = array(); /** * Registers a service factory. * * @param string $id Class name. * @param callable(Container):object $factory Builds the service. * @return void */ public function set( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; unset( $this->instances[ $id ] ); } /** * Returns a shared service. * * @template T of object * @param string $id Class name. * @phpstan-param class-string $id * @return T * @throws RuntimeException When no factory is registered for the class. */ public function get( string $id ): object { if ( ! isset( $this->instances[ $id ] ) ) { if ( ! isset( $this->factories[ $id ] ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Never rendered; developer-facing class name. throw new RuntimeException( "No service registered for {$id}." ); } $this->instances[ $id ] = ( $this->factories[ $id ] )( $this ); } /** @var T */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort return $this->instances[ $id ]; } }