tchwork/closure-caster

Cast closures to single-method implementations

dev-main 2023-04-25 10:09 UTC

This package is auto-updated.

Last update: 2024-04-25 12:17:44 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);