function AutowiredInstanceTrait::createInstanceAutowired
Instantiates a new instance of the implementing class using autowiring.
Parameters
\Symfony\Component\DependencyInjection\ContainerInterface $container: The service container this instance should use.
mixed ...$args: Any predefined arguments to pass to the constructor.
Return value
static
2 calls to AutowiredInstanceTrait::createInstanceAutowired()
- AutowireTrait::create in core/
lib/ Drupal/ Core/ DependencyInjection/ AutowireTrait.php - Instantiates a new instance of the implementing class using autowiring.
- PluginBase::create in core/
lib/ Drupal/ Core/ Plugin/ PluginBase.php - Instantiates a new instance of the implementing class using autowiring.
File
-
core/
lib/ Drupal/ Core/ DependencyInjection/ AutowiredInstanceTrait.php, line 26
Class
- AutowiredInstanceTrait
- Defines a base trait for automatically wiring dependency arguments.
Namespace
Drupal\Core\DependencyInjectionCode
public static function createInstanceAutowired(ContainerInterface $container, mixed ...$args) : static {
if (method_exists(static::class, '__construct')) {
$constructor = new \ReflectionMethod(static::class, '__construct');
foreach (array_slice($constructor->getParameters(), count($args)) as $parameter) {
$service = ltrim((string) $parameter->getType(), '?');
foreach ($parameter->getAttributes(Autowire::class) as $attribute) {
$service = (string) $attribute->newInstance()->value;
}
if (!$container->has($service)) {
if ($parameter->allowsNull()) {
$args[] = NULL;
continue;
}
throw new AutowiringFailedException($service, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s::_construct()", you should configure its value explicitly.', $service, $parameter->getName(), static::class));
}
$args[] = $container->get($service);
}
}
return new static(...$args);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.