Back to results for “Caching Patterns”
PHP › Dependency Injection & Service Containers

How do you bind an interface to a specific concrete implementation within a service container, and why is this a common and valuable pattern?

Intermediate

Answer

Binding an interface to a concrete implementation tells the service container which specific class should be used whenever a class requests that interface as a dependency, which is valuable because it lets the rest of your application depend only on the interface, remaining completely unaware of the specific implementation being used, meaning you can swap the underlying implementation, such as switching from a file based cache to a Redis based cache, by changing just one line of container configuration.
$container->bind(CacheInterface::class, RedisCache::class);

class ReportService {
    public function __construct(private CacheInterface $cache) {}
}
Real-world example A team switches their entire application's caching implementation from file based caching to Redis by changing a single interface binding in their service container configuration, without touching any of the dozens of classes that depend on the caching interface.

Common follow-ups: How do you bind different implementations of the same interface for different specific use cases?;What is the difference between binding a class as shared versus creating a new instance every time?