Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Closure Laravel Package

opis/closure

Serializable closures for PHP: safely capture and transport anonymous functions across processes or requests. Useful for caching, queues, sessions, and distributed jobs, with support for binding, scope, and restoring closures without manual refactoring.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing the package via Composer:

composer require opis/closure

The core API is minimal and intuitive: use Opis\Closure\serialize() and Opis\Closure\unserialize() as drop-in replacements for PHP’s native serialize() and unserialize(). For example:

use Opis\Closure\serialize, Opis\Closure\unserialize;

$closure = function($name) { return "Hello, {$name}!"; };
$serialized = serialize($closure);
$restored = unserialize($serialized);
echo $restored('World'); // Outputs: Hello, World!

Your first use case is likely storing a closure in a cache or queue payload—especially when working with Laravel queues, Redis, or Symfony’s Cache component—where native closures would otherwise fail serialization.

Implementation Patterns

  • Queue Job Payloads: Pass closures as job parameters (e.g., retry callbacks, dynamic filters) without relying on serializable job properties. Example in Laravel:
    dispatch(new ProcessJob(serialize($closure)));
    // Inside the job:
    $fn = unserialize($this->serializedClosure);
    $fn($payload);
    
  • Memoization & Caching: Cache results of expensive computations alongside their closure dependencies:
    $key = md5(serialize($closure) . serialize($args));
    $result = $cache->getOrSet($key, fn() => $closure(...$args));
    
  • Framework-Agnostic Event Hooks: Store event listeners or middleware pipes that include closures across process boundaries (e.g., in message queues or inter-service RPC).
  • Deferred Execution Contexts: Serialize closures in one PHP-FPM process (or CLI) and execute in another worker process (e.g., Swoole, RoadRunner), preserving use() variables and this binding.

Always prefer Opis\Closure\serialize() over native serialize() when closures are involved—no code changes needed beyond the import and wrapper call.

Gotchas and Tips

  • Security: Like any unserialization mechanism, unserialize() can execute arbitrary code if given malicious input. Only untrusted user-provided serialized data in production. For safety, prefer signed payloads or whitelist sources (e.g., own queue jobs).
  • Bound Objects: Closures with bound objects (Closure::bind()) are supported, but the bound object must be serializable. Avoid binding PDO connections or resources—they’ll break during serialization.
  • Performance: Serialization is lightweight but not free. Cache the result where possible (e.g., store pre-serialized closures in constants or config for static reuse).
  • PHP Version Compatibility: While designed for modern PHP, verify support for your environment. The library uses reflection andopinonated AST parsing—rarely fails, but edge cases exist (e.g., closures in compiled PHARs or optimized opcache setups).
  • Debugging: If unserialize() throws Opis\Closure\SerializationException, inspect the exception message—it usually reveals missing dependencies (e.g., use($x) referencing a non-serializable class). Run with Xdebug enabled to trace closure structure during serialization.
  • Extension Tip: Override default serializers via Opis\Closure\Serializer::registerSerializer() if handling custom object types, though this is rarely needed.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope