DI container: insert the right components from the collection of the same type?

I am trying to crack my own dependency injection container in PHP based on constructor injection. The container creates complex objects and enters them with the required objects based on the types of prompts in the constructor using reflection.

One thing that I obviously stumbled upon is the fact that I can register several components that can be injected of the same type (extending the same class / implementing the same interface (s)). For example, what if two objects need different objects that implement the Iterator interface. As usual, do DI Containers handle this? How do you allow the container to decide which of the objects with ambiguous interfaces needs to be entered into which of the complex objects?

Or is it the only container only for the DI container responsible for creating one type of complex object? In other words: an instance of a separate DI container is created for each complex object. I can’t imagine that this is an intention, right?

+3
source share
2 answers

What you are describing is not a DI in itself, but rather autowiring, a step further than a simple DI. Usually with DI you explicitly configure which components connect to what.

Autowired DI , (, DAO). , , "", " ", .

, , Spring autowiring

+1

, , , Guice ( DI Java):

, Foo, Foo.class Foo, Provider<Foo>, , Foo . , Foo, . Foo Foo (, Foo , RealFoo.class, , Foo), - . ( , " ". Guice )

Foo, , : " Foo Bar Baz, Bumble", , , , - :

Foo foo1 = new Foo("1");
Foo foo2 = new Foo("2");
bind(Foo.class).annotatedWith(Names.named("Bar")).toInstance(foo1);
bind(Foo.class).annotatedWith(Names.named("Baz")).toInstance(foo1);
bind(Foo.class).annotatedWith(Names.named("Bumble")).toInstance(foo2);

, Bar - :

public Bar(@Named("Bar") Foo foo) { ...

Baz Bumble. , Bar Baz , bind.

, php , , , , .

+1

Source: https://habr.com/ru/post/1717095/


All Articles