I've got a class hierarchy where I need to be able to instantiate different objects within the hierarchy. Instead of using global functions, I'd like to use injected services from the container via $this
within those objects.
When researching this, it seems as though the only examples I can find involve creating a service, such as Dependency injection in a custom class. However, I don't need a new service. If I did create one, wouldn't I need to create one for every class within the hierarchy so that they could be instantiated? This seems excessive.
If my parent class implements ContainerInjectionInterface
and I have a create()
method to inject the services, can I just instantiate the objects this way, or is it bad practice?
$thing = OneOfMySubClasses::create(\Drupal::getContainer(), ...);