Getting Started
Requires PHP 8.2+.
Use the container for configuring service instantiation and dependency injection. It’s designed as a service container, not a factory, meaning it will instantiate a service only once and return the same instance for all subsequent requests (singleton pattern). If you need to create multiple instances of an object, consider creating a factory service and registering it within the container.
Install
This library is installed using Composer. If you don’t have Composer, you can get it from getcomposer.org.
In your project’s root directory, run the following command:
Create a Configuration
Define your services in a PHP file (e.g., container.php
):
Instantiate the Container
Use the Configurator
class to load your configuration and build the container instance:
Resolve Dependencies
You can now request services from the container using the get()
method:
Putting It All Together
Example:
In this example:
- We require Composer’s autoloader.
- We define a
Logger
service incontainer.php
. - We instantiate the
Configurator
, load the configuration file, and build the container. - We get the
logger
service from the container and use it to log a message.
Key Points to Remember:
- Service IDs: Use descriptive names for your service IDs to make your configuration readable.
- Dependency Resolution: The container automatically resolves dependencies between your services based on type hints and the configuration you provide.
- Singleton Scope: Services are created as singletons, meaning the container will return the same instance each time you request it.