*/ private array $factories = array(); /** * Уже созданные сервисы. * * @var array */ private array $instances = array(); /** * Регистрирует фабрику сервиса. * * @param string $id Идентификатор (обычно FQCN). * @param callable(self): object $factory Фабрика. */ public function set( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; unset( $this->instances[ $id ] ); } /** * Возвращает сервис, создавая его при первом обращении. * * @template T of object * @param class-string|string $id Идентификатор сервиса. * @return T|object * * @throws RuntimeException Если сервис не зарегистрирован. */ public function get( string $id ): object { if ( isset( $this->instances[ $id ] ) ) { return $this->instances[ $id ]; } if ( ! isset( $this->factories[ $id ] ) ) { throw new RuntimeException( esc_html( sprintf( 'Service "%s" is not registered in the container.', $id ) ) ); } $this->instances[ $id ] = ( $this->factories[ $id ] )( $this ); return $this->instances[ $id ]; } /** * Зарегистрирован ли сервис. * * @param string $id Идентификатор сервиса. */ public function has( string $id ): bool { return isset( $this->factories[ $id ] ); } }