Classes that implement \Drupal\Core\DependencyInjection\ContainerInjectionInterface must provide a create() factory method to instantiate the object.
Now that services can be autowired and plugins can be autowired, the FormBase class has also been extended with AutowireTrait, providing a generic version of the create() method suitable for most forms that need dependency injection.
Previously, a constructor and create() method would be something like this:
public function __construct(EntityDisplayRepositoryInterface $entity_display_repository, ConfigFactoryInterface $config_factory) {
$this->entityDisplayRepository = $entity_display_repository;
$this->configFactory = $config_factory;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_display.repository'),
$container->get('config.factory')
);
}
Now it is possible to drop the create() method:
public function __construct(EntityDisplayRepositoryInterface $entity_display_repository, ConfigFactoryInterface $config_factory) {
$this->entityDisplayRepository = $entity_display_repository;
$this->configFactory = $config_factory;
}
In simple cases, the service can be inferred from the interface name alone. If a service cannot be determined from the interface directly, an exception will be raised, and you can add the #[Autowire] attribute to specify the service ID.