In this episode, we tackle a pretty important refactor: shifting our container setup over to use the Singleton pattern. Right now, our dependency injection container just lives as a local variable inside our bootstrap files, which is fine for startup—but kinda awkward once your app grows and you need to grab stuff from the container all over the place.
We start by creating a Container
class in our core directory. Inside, we set up the typical PHP Singleton: a static property for the instance, and a static getInstance
method. This ensures that throughout our app, we're always using the same container instance, and we can grab it from anywhere at runtime. It's a super useful pattern for these sorts of application-wide dependencies.
After implementing the Singleton, we refactor our bootstrap and other files to use Container::getInstance()
instead of manually passing the container variable around. We also catch a minor mistake (making sure the getInstance
method is actually static!), and show that you can now resolve dependencies from anywhere in your code—much cleaner!
Finally, we clean up some example classes we no longer need, leaving us in a much tidier state, with the groundwork laid for more flexible, maintainable code as the course continues.