You are here

public function ClassResolver::getInstanceFromDefinition in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/DependencyInjection/ClassResolver.php \Drupal\Core\DependencyInjection\ClassResolver::getInstanceFromDefinition()

Returns a class instance with a given class definition.

In contrast to controllers you don't specify a method.

Parameters

string $definition: A class name or service name.

Return value

object The instance of the class.

Throws

\InvalidArgumentException If $class is not a valid service identifier and the class does not exist.

Overrides ClassResolverInterface::getInstanceFromDefinition

File

core/lib/Drupal/Core/DependencyInjection/ClassResolver.php, line 23
Contains \Drupal\Core\DependencyInjection\ClassResolver.

Class

ClassResolver
Implements the class resolver interface supporting class names and services.

Namespace

Drupal\Core\DependencyInjection

Code

public function getInstanceFromDefinition($definition) {
  if ($this->container
    ->has($definition)) {
    $instance = $this->container
      ->get($definition);
  }
  else {
    if (!class_exists($definition)) {
      throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $definition));
    }
    if (is_subclass_of($definition, 'Drupal\\Core\\DependencyInjection\\ContainerInjectionInterface')) {
      $instance = $definition::create($this->container);
    }
    else {
      $instance = new $definition();
    }
  }
  if ($instance instanceof ContainerAwareInterface) {
    $instance
      ->setContainer($this->container);
  }
  return $instance;
}