Back to Registry class

Method register

public void
register
(string $key, mixed $handler, bool $replace = false)
Register a service
Parameters
  • string $key The service key to be registered
  • string|object $handler The handler for the service as either a PHP class name or class object
  • bool $replace Flag indicating the service key may replace an existing definition
Returns
  • void
Since
  • 4.0.0
Class: Registry
Project: Joomla

Method register - Source code

/**
 * Register a service
 *
 * @param   string         $key      The service key to be registered
 * @param   string|object  $handler  The handler for the service as either a PHP class name or class object
 * @param   boolean        $replace  Flag indicating the service key may replace an existing definition
 *
 * @return  void
 *
 * @since   4.0.0
 */
public function register(string $key, $handler, bool $replace = false)
{
    // If the key exists already and we aren't instructed to replace existing services, bail early
    if (isset($this->serviceMap[$key]) && !$replace) {
        throw new \RuntimeException("The '{$key}' service key is already registered.");
    }
    // If the handler is a string, it must be a class that exists
    if (\is_string($handler) && !class_exists($handler)) {
        throw new \RuntimeException("The '{$handler}' class for service key '{$key}' does not exist.");
    }
    // Otherwise the handler must be a class object
    if (!\is_string($handler) && !\is_object($handler)) {
        throw new \RuntimeException(sprintf('The handler for service key %1$s must be a PHP class name or class object, a %2$s was given.', $key, \gettype($handler)));
    }
    $this->serviceMap[$key] = $handler;
}