SLs: equivalent of an associative array Set objects at bootstrap Retrieve objects when requested Objects may be instantiated lazily (only when you ask for them, think via PHP 5's closures)
public methods are an API to the object's usage • How the methods can be used should be visible from the method signatures alone Pass in your container = a container dependency, hard to test etc Pass in your object = we know exactly what the object needs to run
• Logging • Database • Other registered services • Let's go check the docs... (to the developer writing it) $foo contains: • No idea... • Let's go check the docs... (to a future developer)
Location SL = simpler, but couples service to container DI = Testable code, but time consuming to set up and configure Method requirements should be visible from the method signature only Constructor-only injection in your controllers shares objects that may not need to be shared Note: we're not talking about setter injection here Method injection in your controllers provides a clear explanation of the method's needs Controllers don't always adhere to SRP anyway
as close to the top layer as possible ie. in your bootstrap In PHP, this could involve: Sequentially manually created objects An array of object mappings as strings A configuration file containing mappings
signature of MyService 2. Sees the typehint for DatabaseObject 3. Uses reflection to read the method signature for DatabaseObject 4. No dependencies here, creates the DatabaseObject and injects it into MyService
signature of MyService 2. Sees the typehint for DatabaseObject 3. Uses reflection to read the method signature for DatabaseObject 4. No dependencies here, creates the DatabaseObject and injects it into MyService Do this in your composition root Do this in your controller resolver
concrete class When "MyService" is resolved: 1. The constructor signature will be read via reflection 2. The DatabaseInterface will be found as a dependency 3. The alias for DatabaseInterface is "MongoDbInstead" 4. The MongoDbInstead class is dependency injected for us