Lazy loading
The main feature of this minor release is the lazy loader. Use the setLoader()
method of the Container
class to pass a callback that constructs your dependency, rather than having to have a pre-constructed object when using the set()
method.
An often overlooked benefit of using service containers is the fact that, as the framework knows when and where a service is being requested, it doesn't actually need to construct the object until the first time it's requested.
A good example of where this will benefit is the Database. Using a lazy-loaded service container has two implementation benefits:
- On pages that don't query the database, the database object is never constructed, so no connections are made to the database until they're used.
- The framework can suggest default behaviour for the construction of objects, but if the developer wants to use a different implementation of the same interface, they are free to override it.
The other benefit is how the container is used: the developer can register their own classes in the container, again only being constructed at use-time, allowing much richer abstraction patterns like the Repository Pattern hiding any database implementations.