Container::get

public Container::get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)

File

core/lib/Drupal/Component/DependencyInjection/Container.php, line 136

Class

Container
Provides a container optimized for Drupal's needs.

Namespace

Drupal\Component\DependencyInjection

Code

public function get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
  if (isset($this->aliases[$id])) {
    $id = $this->aliases[$id];
  }

  // Re-use shared service instance if it exists.
  if (isset($this->services[$id]) || ($invalid_behavior === ContainerInterface::NULL_ON_INVALID_REFERENCE && array_key_exists($id, $this->services))) {
    return $this->services[$id];
  }

  if (isset($this->loading[$id])) {
    throw new ServiceCircularReferenceException($id, array_keys($this->loading));
  }

  $definition = isset($this->serviceDefinitions[$id]) ? $this->serviceDefinitions[$id] : NULL;

  if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
    if (!$id) {
      throw new ServiceNotFoundException($id);
    }

    throw new ServiceNotFoundException($id, NULL, NULL, $this->getServiceAlternatives($id));
  }

  // In case something else than ContainerInterface::NULL_ON_INVALID_REFERENCE
  // is used, the actual wanted behavior is to re-try getting the service at a
  // later point.
  if (!$definition) {
    return;
  }

  // Definition is a keyed array, so [0] is only defined when it is a
  // serialized string.
  if (isset($definition[0])) {
    $definition = unserialize($definition);
  }

  // Now create the service.
  $this->loading[$id] = TRUE;

  try {
    $service = $this->createService($definition, $id);
  }
  catch (\Exception $e) {
    unset($this->loading[$id]);
    unset($this->services[$id]);

    if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
      return;
    }

    throw $e;
  }

  unset($this->loading[$id]);

  return $service;
}
doc_Drupal
2016-10-29 08:56:37
Comments
Leave a Comment

Please login to continue.