Skip to content

Dependency injection into a parameter with an interface type ​

In certain container usage scenarios, it is necessary to be able to declare a dependency injection within a method parameter or a callable type[1] that expects an object implementing a specific interface.

Such an object can be injected by associating the interface's FQCN[2] with a specific PHP class, allowing the container to automatically inject the required object.

The container offers various ways to implement such a declaration, depending on the specific task at hand.

IMPORTANT

The PHP class object retrieved from the dependency injection container must implement the interface expected by the parameter.


Globally register ​

You can globally register a specific PHP class as the implementation of an interface within the container; the container will then automatically inject this implementation whenever an interface is required, unless a different implementation has been explicitly specified for a particular method parameter or type being invoked.

To globally register an interface implementation, you must specify the interface name as the container identifier[3] and provide its implementation – either via a helper function or by using the \Kaspi\DiContainer\Attributes\Service attribute.

💡 Examples of global interface implementation registration.


Declaration of an insertion into a specific parameter ​

For a method parameter or a type being instantiated that is represented by a specific interface, you can declare a dependency injection that differs from the global implementation defined for that interface.

You can declare dependency injection for such a parameter using a helper function or attributes.

💡 Examples of declaring dependency injection for a specific parameter.


  1. The callable type represents values ​​or expressions that can be invoked as a function. See the description in the PHP documentation. ↩︎

  2. Fully Qualified Class Name – the full name of a class or interface, including its namespace. ↩︎

  3. A container ID is a string name (or a class/interface name) used to register a service or object within a container and to retrieve it via the get() method. ↩︎