trait AutowireTrait

Same name in other branches
  1. 10 core/lib/Drupal/Core/DependencyInjection/AutowireTrait.php \Drupal\Core\DependencyInjection\AutowireTrait

Defines a trait for automatically wiring dependencies from the container.

This trait uses reflection and may cause performance issues with classes that will be instantiated multiple times.

Hierarchy

1 file declares its use of AutowireTrait
ControllerBase.php in core/lib/Drupal/Core/Controller/ControllerBase.php

File

core/lib/Drupal/Core/DependencyInjection/AutowireTrait.php, line 15

Namespace

Drupal\Core\DependencyInjection
View source
trait AutowireTrait {
    
    /**
     * Instantiates a new instance of the implementing class using autowiring.
     *
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     *   The service container this instance should use.
     *
     * @return static
     */
    public static function create(ContainerInterface $container) {
        $args = [];
        if (method_exists(static::class, '__construct')) {
            $constructor = new \ReflectionMethod(static::class, '__construct');
            foreach ($constructor->getParameters() as $parameter) {
                $service = ltrim((string) $parameter->getType(), '?');
                foreach ($parameter->getAttributes(Autowire::class) as $attribute) {
                    $service = (string) $attribute->newInstance()->value;
                }
                if (!$container->has($service)) {
                    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);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overrides
AutowireTrait::create public static function Instantiates a new instance of the implementing class using autowiring. 33

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.