jeremeamia/superclosure
Serialize and unserialize PHP Closures/anonymous functions, including use() context, via fast TokenAnalyzer or more robust AstAnalyzer. Note: project is no longer maintained; consider using opis/closure instead.
jeremeamia/superclosure lets you serialize PHP closures — something PHP doesn’t natively support. Despite being unmaintained since 2018 (and explicitly discouraged for new projects in favor of opis/closure), it still works well in legacy codebases or constrained environments where it’s already in use.
First steps:
composer require jeremeamia/superclosureSerializer and serialize/unserialize closures as needed:use SuperClosure\Serializer;
$serializer = new Serializer();
$closure = function ($name) { echo "Hello, $name!"; };
$serialized = $serializer->serialize($closure);
$unserialized = $serializer->unserialize($serialized);
$unserialized('World'); // outputs: Hello, World!
This is especially useful when storing closures for delayed execution — e.g., queuing jobs (Laravel historically used it for IronMQ jobs), caching router/container definitions, or persisting simple callable tasks.
$queue->push($serializer->serialize(function ($payload) {
sendEmail($payload['to'], $payload['subject']);
}));
$key = 'router_closures';
$routes = $cache->get($key) ?: $serializer->serialize($router->getClosures());
$cache->put($key, $routes, 3600);
AstAnalyzer (default) or TokenAnalyzer to introspect closure structure, bindings, scope, and code for debugging or tooling.use SuperClosure\Analyzer\AstAnalyzer;
$analyzer = new AstAnalyzer();
$metadata = $analyzer->analyze($fn); // includes code, context, binding, location, etc.
$serializer = new Serializer(null, 'your-super-secret-signing-key');
$signed = $serializer->serialize($fn);
// Later, unserialize safely — invalid signatures throw `ClosureUnserializationException`
$fn = $serializer->unserialize($signed);
eval() is required during unserialization — always verify serialized data sources are trusted. Prefer signing, and sanitize/unpack closures in restricted contexts (e.g., internal queues, local caches).use (&$self)).eval() — including unserialized closures (no re-serialization allowed).TokenAnalyzer is ~20× faster but lacks support for class type hints in params/body, static closures, magic constants, etc. Use AstAnalyzer for completeness unless performance is critical.opis/closure, which has better docs, active maintenance, and fewer eval() risks (supports AST-based code generation).opis/closure or explicit job classes instead of closures for serialization.How can I help you explore Laravel packages today?