Understanding Object Lifecycles
The Service Container offers three methods to control how and when objects are created. Watch them in action below:
bind()
Creates a NEW instance every time
First Resolution
report_693d4ea02902b
Second Resolution
report_693d4ea02903c
✅ Perfect! Each call to app(ReportGenerator::class) creates a NEW instance
Use Case: Independent operations (reports, validators, calculators)
singleton()
Reuses the SAME instance throughout request
First Resolution
config_693d4ea0292f9
Second Resolution
config_693d4ea0292f9
✅ Perfect! Both resolutions return the SAME instance (singleton pattern)
Efficiency: Configuration loaded only 1 time(s) - saved resources by reusing the instance!
Use Case: Expensive-to-create services (DB connections, config loaders)
Quick Comparison
| Method | Lifecycle | When to Use |
|---|---|---|
| bind() | New instance every time | Independent operations, stateless services |
| singleton() | One instance per request | Expensive to create, maintains state |
| instance() | Pre-configured object | Complex setup before binding |
💡 Pro Tip
Rule of thumb: Use singleton() for services that
don't change during a request (DB connections, cache managers, config loaders). Use bind()
when each usage should be independent (validators, calculators, report generators).