zenstruck/callback
Tiny PHP utility for building and composing callbacks/closures with a fluent API. Helps wrap callables, bind arguments, decorate or chain behavior, and safely invoke functions and methods—handy for middleware-style pipelines, event hooks, and reusable functional helpers.
composer require zenstruck/callbackCallback:
use Zenstruck\Callback;
$callback = Callback::from(fn() => 'Hello world');
echo $callback(); // Invokes the wrapped callable
$callback = Callback::from('strlen'); // Built-in function
$callback = Callback::from([MyService::class, 'handle']); // Static method
$callback = Callback::from($myObject); // Invokable object
Callback class and its static from() factory — that’s your main entry point. Check Callback::__toString() for a human-readable description (great for logs or debugging).Callback for consistent type-hinting (Callback $callback) and safer dispatching.Callback implements __toString() with a normalized representation (e.g., "App\Commands\Handler::handle"), it’s easier to serialize/deserialize than closures (which are unserializable in many contexts).Callback objects to get meaningful output in logs or developer tools:
logger((string) $callback); // "MyListener::onUserLogin"
Callback::from(Closure::fromCallable([MyService::class, 'process']));
Callback instances as JSON-safe strings in job payloads — ideal for deferred or scheduled work where closures won’t serialize cleanly.Callback attempts to represent them as "Closure @line X in file Y", but don’t rely on round-tripping them across processes (e.g., queues). Prefer named callables (methods, static calls, invokables).Callback::from() is smart: It auto-detects Class@method strings, invokables, and arrays — but be explicit when passing closures (use Closure::fromCallable() or just pass them directly; from() handles them, but representation won’t be meaningful).Callback forwards __invoke() to the wrapped callable — but any exceptions (e.g., missing class/method) bubble up normally. Wrap invocations in try/catch if used in user-facing contexts.Callback::debug($callback) gives a nicely formatted string (using __toString() internally) — useful for dd() or logging.Callback and CallbackFactory. If you need custom representation (e.g., anonymized method names), extend Callback and override __toString().How can I help you explore Laravel packages today?