tchwork / closure-caster
Cast closures to single-method implementations
dev-main
2023-04-25 10:09 UTC
Requires
- symfony/var-exporter: ^6.2.10
Requires (Dev)
- phpunit/phpunit: ^10.2
This package is auto-updated.
Last update: 2024-10-25 13:20:32 UTC
README
This package provides a function named closure_cast_to()
that allows
turning a closure into an object implementing a single-method interface.
Imagine you have an interface like this:
interface TranslatorInterface { public function translate(string $message, $parameters = []): string; }
And that the strtr()
function is a correct implementation for the identity translator.
You can get an instance of TranslatorInterface
delegating to strtr()
like this:
$identityTranslator = closure_cast_to(strtr(...), TranslatorInterface::class);
This package is meant as a proof-of-concept implementation of
this RFC
which proposes to add a new castTo
method to the native Closure
class so that the previous example could be written like this:
$identityTranslator = strtr(...)->castTo(TranslatorInterface::class);