Symfony/Contracts, a set of abstractions extracted from the Symfony components, are designed to build on semantic ideas that have proved useful within the Symfony components, and which have been implementatively tested. These contracts are small and consistent sets of PHP interfaces, traits, normative docblocks, and reference test suites where applicable. All contracts must have a proven implementation to enter this repository and are required to be backward compatible with existing Symfony components.
You can utilize Symfony/Contracts to achieve loose coupling and interoperability in your coding. By using the interfaces provided as type hints within your code, you improve reusability as implementations that match the contracts can be utilized. It could be a Symfony component or another one provided by the PHP community at large. Here's an example of how that might look in your code:
// use the Cache contract
use Symfony\Contracts\Cache\CacheInterface;
// ...
public function someFunction(CacheInterface $cache)
{
// use the cache service
$value = $cache->get('some_key', function ($item) {
// The code here will only run if there is no existing cache for 'some_key'
$item->expiresAfter(3600);
return 'Some expensive resource';
});
}
In this code, you're using the CacheInterface
from Symfony/Contracts as a type hint in a function. This means that you can pass in any implementation of the CacheInterface
into this function, and it will work as expected.
Depending on their semantics, some interfaces can be combined with autowiring to seamlessly inject a service in your classes. Others might be valuable as labeling interfaces to hint at specific behavior that could be enabled when using autoconfiguration or manual service tagging.
The Symfony/Contracts resources are available on the Symfony website. Documentation pertaining to Symfony/Contracts can be found at this URL: https://symfony.com/doc/current/components/contracts.html. In these documents, you can learn more details about what each contract does, and how to use them efficiently. Also, for contributing to the Symfony/Contracts project, you can crosscheck this link: https://symfony.com/doc/current/contributing/index.html. Any issues and pull requests can be reported and sent respectively in the main Symfony repository: https://github.com/symfony/symfony.