The Container class, located in the DInjection\Container
namespace, serves as the core component of dependency management. It enables you to register services, resolve dependencies, handle singletons, and bind implementations to interfaces or abstract classes like Laravel service container
. For understanding the logic behind laravel service container I decided to create my own.
To begin using the Container, follow these steps:
-
Installation: Simply include the Container class in your project. There are no additional dependencies required.
$container = Container::getInstance();
-
Registering Services: Use the
register
method to add services to the container. You can register services using closures or class names.$container->register('service', fn() => new SomeService());
-
Resolving Dependencies: Utilize the
get
method to resolve dependencies from the container. The container will automatically instantiate objects and inject dependencies as needed.$service = $container->get('service');
-
Handling Singletons: If you need a service to be a singleton (i.e., a single instance shared across multiple requests), use the
singleton
method.$container->singleton('service', fn() => new SomeService());
-
Binding Implementations: You can bind implementations to interfaces or abstract classes using the
register
orsingleton
methods.$container->register(Writeable::class, Writer::class);
-
Checking Service Existence: Determine if a service is registered in the container using the
has
method.if ($container->has('service')) { // Service exists }
-
Exception Handling: The container throws exceptions if it encounters issues, such as attempting to instantiate abstract types or non-existent services.