3 December 2024

The issue comes down to picking ControllerBase or ContainerInjectionInterface. Here is a simple explanation between the two paths of ControllerBase vs ContainerInjectionInterface.

1. ControllerBase vs. ContainerInjectionInterface

  • ControllerBase:
    • A base class in Drupal that provides commonly used methods and access to services through dependency injection.
    • Using it means you inherit all its methods, including service access. However, in testing, you need to mock or replace those services to avoid dependencies on real implementations.
  • ContainerInjectionInterface:
    • A Drupal interface that allows a class to declare its dependencies explicitly via the create() method.
    • You don’t get automatic access to services. Instead, you explicitly define which services you want and import them using traits or the container. This approach is more test-friendly, as you only mock the services you explicitly declare.

2. Difference Between extend and implement

  • Extend:
    • Inherit behavior from a parent class. You get all the parent class's methods and properties, which you can override as needed.
    • Example: class MyController extends ControllerBase.
  • Implement:
    • Commit a class to fulfilling the contract defined by an interface. You must provide implementations for all the interface's methods.
    • Example: class MyService implements ContainerInjectionInterface.

Summary

ControllerBase is convenient but tightly couples your controller to all its inherited dependencies.
ContainerInjectionInterface requires more setup but provides better control and testability.
Extend = inheritance (reuse and override), Implement = fulfill a contract (customize as needed).