Featured image of post What are the logical differences between bind(), singleton(), scoped(), and instance() in Laravel? In what situations can they be used?

What are the logical differences between bind(), singleton(), scoped(), and instance() in Laravel? In what situations can they be used?

What are the logical differences between bind(), singleton(), scoped(), and instance() in Laravel? In what situations can they be used?

Comparison of Object Binding Methods in Laravel Service Container

Method bind() singleton() scoped() instance()
Description Creates a new instance every time it is resolved. Only creates one instance and returns the same instance on subsequent requests. Creates one instance only during each request/job lifecycle, which is cleared after the request ends. Binds an existing instance to the container, returning that instance every time it is resolved.
Advantages - Each request is a brand new instance, no state sharing issues
- Clean memory usage
- Suitable for handling logic that requires independent state
- Can provide unique configuration for each request
- Saves system resources, only needs to create the instance once
- Ensures state consistency
- Suitable for shared configuration and resources
- Performs better under high concurrency
- Balances memory usage and state sharing
- Shares state within the request but isolates between requests
- Suitable for web request scenarios
- Complete control over when the instance is created
- Can pre-configure the instance state
- Suitable for services that require specific configuration
Disadvantages - Requires more system resources to repeatedly create instances
- May affect performance under high concurrency
- Not suitable for scenarios that require shared state
- May lead to performance issues as a new instance is created each time.
- Shared state may lead to hard-to-trace bugs
- Not suitable for scenarios that require independent state
- Memory usage persists until the program ends
- Testing requires special attention to state reset
- If the instance holds state, it may lead to unexpected behavior.
- May encounter issues in long-running tasks
- Requires understanding of the request lifecycle
- Not suitable for CLI commands
- Less flexible
- Cannot dynamically adjust instance configuration
- May occupy memory at startup
- Not suitable for scenarios that require lazy loading or multiple instances.
Usage Scenarios Used for services that are short-lived or require independent state. Used for globally shared services, such as loggers or configuration managers. Used for services that need to maintain state within a request but not across requests, such as database connections. When you already have an instance and want to reuse it, such as a shared configuration object.
Examples When you have a Product class and want to create a new Product instance each time different product data is requested. When you have a Logger class and want all logging operations to use the same instance for consistency. When you have a ShoppingCart class that needs to share the cart state within the same request. When you have a DatabaseConfig class that needs to set up connection parameters at application startup.

Examples

Using bind()

$this->app->bind('Product', function () {
 return new Product();
});

Each time app('Product') is called, it will return a new Product instance.

Using singleton()

$this->app->singleton('Logger', function () {
 return new Logger();
});

Each time app('Logger') is called, it will return the same Logger instance.

Using scoped()

$this->app->scoped(Transistor::class, function (Application $app) {
    return new Transistor($app->make(PodcastParser::class));
});

It shares the same instance within the same request lifecycle, but creates a new instance for different requests.

Using instance()


$service = new Transistor(new PodcastParser);
 
$this->app->instance(Transistor::class, $service);

It directly binds an existing instance to the container.

Summary

Laravel can currently be applied in many different types of scenarios, such as Web requests, CLI commands, Queue jobs, Console commands, and so on.

Therefore, when choosing which binding method to use, it is necessary to consider the needs of the service in different scenarios, as well as whether state sharing or configuration is required.

Reference

All rights reserved,未經允許不得隨意轉載
Built with Hugo
Theme Stack designed by Jimmy