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