I am relatively fresh to the DI party and am struggling to get my head around how exactly to use Dependency Injection. I understand that I can pass requirements as part of a service, but what about in my own class?
Say I have the below class where I want the language manager service to be injected:
class Foo implements ContainerInjectionInterface {
protected $languageManager;
public function __construct(LanguageManagerInterface $languageManager) {
$this->languageManager = $languageManager;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('language_manager')
);
}
}
When I call new Foo()
I am required to pass an instance of LanguageManagerInterface. That makes sense in terms of a normal constructor method, but that would require me to instantiate the class like the below:
$languageManager = \Drupal::service('language_manager');
$foo = new Foo($languageManager)
That just doesn't feel right to me.
Is there something I am missing, or would this class always have to be a service to take advantage of dependency injection?