symfony/service-contracts
Symfony Service Contracts provides lightweight, battle-tested abstractions extracted from Symfony components. Use these shared interfaces to build interoperable libraries and apps with proven semantics and consistent behavior across the Symfony ecosystem.
Start by installing the package via Composer:
composer require symfony/service-contracts
This package contains only interfaces, so it won’t add runtime behavior until you integrate it into a DI-aware context (e.g., Symfony’s DependencyInjection component or Laravel’s container with适配). Your first immediate use case is likely implementing ServiceSubscriberInterface in services like Laravel command handlers or job classes to declare dependencies declaratively—e.g., fooService(): FooService—instead of constructor injection. Review the ServiceSubscriberInterface and ServiceLocator contracts first; they’re the most practical entry points for decoupling service usage.
ServiceSubscriberInterface in ShouldQueue jobs or Artisan commands. Combine with Laravel’s container (which implements Psr\Container\ContainerInterface) to resolve services lazily via a ServiceLocator. Avoids bloating constructor signatures for rarely-used dependencies (e.g., SMS, email, or third-party API clients).ServiceLocator to inject collections of related services (e.g., multiple EventSubscriberInterface implementations in a domain layer) without circular dependency risks or tight coupling.ServiceSubscriberInterface instead of concrete types. This lets consumers pass any PSR-11-compliant service locator (including Laravel’s container) without hard dependency on Symfony.ServiceLocator with mock services (e.g., new ServiceLocator(['mailer' => $mockMailer])) and inject it into subscribers—eliminates full container bootstrapping and improves test speed.php artisan list or Route::get()—it works silently under DI containers. Verify integration with Laravel’s App::make() or Container::bind() logic.Container implements Psr\Container\ContainerInterface, but some older implementations or custom extensions might not. Confirm compatibility via app()->get('foo') works before relying on ServiceSubscriberInterface.ServiceLocator instances that resolve short-lived services (e.g., request(), session())—this can cause stale references or memory leaks. Use constructor injection for per-request dependencies instead.ServiceSubscriberTrait throws ServiceNotFoundException for unbound services. Override defaultServices or extend ServiceSubscriberTrait to customize fallback behavior (e.g., return null or throw a domain-specific exception).composer require symfony/contracts to align versions—especially symfony/dependency-injection, which integrates tightly with these contracts.How can I help you explore Laravel packages today?