You are here

class ServiceContainer in X Autoload 7.5

Same name and namespace in other branches
  1. 7.4 lib/DIC/ServiceContainer.php \Drupal\xautoload\DIC\ServiceContainer

Hierarchy

Expanded class hierarchy of ServiceContainer

See also

ServiceFactory

2 files declare their use of ServiceContainer
Main.php in src/Main.php
xautoload.early.lib.inc in ./xautoload.early.lib.inc

File

src/DIC/ServiceContainer.php, line 8

Namespace

Drupal\xautoload\DIC
View source
class ServiceContainer implements ServiceContainerInterface {

  /**
   * @var ServiceFactory
   */
  protected $factory;

  /**
   * @var object[]
   */
  protected $services = array();

  /**
   * @param string $key
   *
   * @return mixed
   */
  function get($key) {
    return isset($this->services[$key]) ? $this->services[$key] : ($this->services[$key] = $this->factory
      ->{$key}($this) ?: FALSE);
  }

  /**
   * Unset the service for a specific key.
   *
   * @param string $key
   */
  function reset($key) {
    $this->services[$key] = NULL;
  }

  /**
   * Register a new service under the given key.
   *
   * @param string $key
   * @param mixed $service
   */
  function set($key, $service) {
    $this->services[$key] = $service;
  }

  /**
   * Magic getter for a service.
   *
   * @param string $key
   *
   * @return mixed
   *
   * @throws \Exception
   */
  function __get($key) {
    if (isset($this->services[$key])) {
      return $this->services[$key];
    }
    if (!method_exists($this->factory, $key)) {
      throw new \Exception("Unsupported key '{$key}' for service factory.");
    }
    return $this->services[$key] = $this->factory
      ->{$key}($this) ?: FALSE;
  }

  /**
   * @param ServiceFactory $factory
   */
  function __construct($factory) {
    $this->factory = $factory;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ServiceContainer::$factory protected property
ServiceContainer::$services protected property
ServiceContainer::get function
ServiceContainer::reset function Unset the service for a specific key.
ServiceContainer::set function Register a new service under the given key.
ServiceContainer::__construct function
ServiceContainer::__get function Magic getter for a service. Overrides ServiceContainerInterface::__get