The Service Container is one of Laravel's core features. It is Laravel's implementation of the Dependency Injection (DI) and Inversion of Control (IoC) patterns.
It's also Laravel's way of managing dependencies and injecting them automatically.
Instead of creating dependencies manually with the new keyword, you let the container resolve and inject them for you.
How Laravel Uses the Service Container
Most Service Container bindings are registered inside Service Providers using the register() method.
Within a service provider, you have access to the container through the $this->app property.
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
}
}
- Use the bind() method to tell Laravel how to create an object. Every time the dependency is resolved, Laravel creates a new instance.
Exaple
Whenever someone requests LoggerInterface, Laravel should create and return a new FileLogger instance.
$this->app->bind(LoggerInterface::class, function () {
return new FileLogger();
});
- Use singleton() when you want Laravel to create only one instance and reuse it throughout the application's lifetime.
Exaple
The first time CacheService is requested, Laravel creates the object.
Every subsequent request returns the same instance instead of creating a new one.
$this->app->singleton(CacheService::class, function () {
return new CacheService();
});
$one = app(CacheService::class);
$two = app(CacheService::class);
var_dump($one === $two); // true
bind() vs singleton()
bind(): Creates a new instance every time the dependency is resolved.
singleton(): Creates one instance and reuses it for all future resolutions.
Note:
You will typically be interacting with the container within service providers; however, if you would like to interact with the container outside of a service provider, you may do so via the App facade
There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.
Exaple
If your class has no constructor parameters (or only concrete classes, not interfaces), Laravel will automatically create it β you donβt have to register it.
class HelloService {
public function sayHello() {
return 'Hello!';
}
}
$service = app(HelloService::class);
Top comments (0)