ClassResolver::getInstanceFromDefinition

public ClassResolver::getInstanceFromDefinition($definition)

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 18

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;
}
doc_Drupal
2016-10-29 08:50:01
Comments
Leave a Comment

Please login to continue.