Dependency injection and the service locator
Something you may have realized when looking at ToyMVC is the fact that there is quite a lot of work going on to build instances of objects. Also, you could imagine that if the app grew to real-world sizes, then the amount of work that would need to be done in AppFactory
could become quite substantial.
Furthermore, due to the complexity of building up a large graph of object instances, there is also the issue that this is generally going to be very wasteful. PHP's requests are not stateful and when instantiating an MVC app, it is almost certain to serve one – and only one – request. There is no need to fire up instances of every single piece of the application when we may not need them all.
Thankfully, there is now a widely accepted best practice solution for this that is incredibly developer-friendly – dependency injection, or DI for short.
Now, I say this is developer-friendly, but that does not mean...