*/ private $factories = array(); /** * Ids that must resolve to a single shared instance. * * @var array */ private $shared = array(); /** * Resolved shared instances. * * @var array */ private $instances = array(); /** * Registers a service that is built once and then reused. * * @since 0.1.0 * * @param string $id Service id, normally the class name. * @param callable $factory Receives the container, returns the service. * @return void */ public function singleton( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; $this->shared[ $id ] = true; unset( $this->instances[ $id ] ); } /** * Registers a service that is built again on every request for it. * * @since 0.1.0 * * @param string $id Service id. * @param callable $factory Receives the container, returns the service. * @return void */ public function bind( string $id, callable $factory ): void { $this->factories[ $id ] = $factory; $this->shared[ $id ] = false; unset( $this->instances[ $id ] ); } /** * Tells whether a service id is registered. * * @since 0.1.0 * * @param string $id Service id. * @return bool */ public function has( string $id ): bool { return isset( $this->factories[ $id ] ); } /** * Resolves a service. * * @since 0.1.0 * * @param string $id Service id. * @return mixed * * @throws RuntimeException When the id is not registered. */ public function get( string $id ) { if ( ! $this->has( $id ) ) { // The id is a developer-supplied class name, never user input, and this class stays WordPress-free for unit testing. throw new RuntimeException( sprintf( 'HostKhata service "%s" is not registered.', $id ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( ! $this->shared[ $id ] ) { return call_user_func( $this->factories[ $id ], $this ); } if ( ! array_key_exists( $id, $this->instances ) ) { $this->instances[ $id ] = call_user_func( $this->factories[ $id ], $this ); } return $this->instances[ $id ]; } }