Skip to content

Cast closures to single-method implementations

License

Notifications You must be signed in to change notification settings

tchwork/closure-caster

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tchwork/closure-caster

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);

About

Cast closures to single-method implementations

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Languages