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

Curry Laravel Package

react/curry

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Verify Deprecation**: Confirm this package is deprecated and replaced by [`react/partial`](https://github.com/reactphp/partial). Do **not** use `react/curry` in new projects.
2. **Installation (Legacy Only)**:
   ```bash
   composer require react/curry
  1. First Use Case:
    use React\Curry\Curry;
    
    // Partial application (not currying)
    $add = function ($a, $b) { return $a + $b; };
    $addFive = Curry::apply($add, 5);
    $result = $addFive(3); // Returns 8
    
  2. Where to Look First:
    • ReactPHP Partial Docs (replacement package).
    • Laravel’s built-in closures (Closure::bind()) for simpler cases.

Implementation Patterns

Usage Patterns

  1. Event Listeners with Pre-Bound Args
    use React\Curry\Curry;
    
    Event::listen('user.registered', Curry::apply(
        [$notifier, 'sendEmail'],
        'welcome'
    ));
    
  2. Middleware with Partial Arguments
    $middleware = Curry::apply(
        \App\Http\Middleware\Authenticate::class,
        ['guard' => 'admin']
    );
    
  3. Service Container Integration
    $this->app->bind('partial.add', function () {
        return Curry::apply(fn($a, $b) => $a + $b, 10);
    });
    
  4. Queue Jobs with Partial Logic
    $processOrder = Curry::apply(
        [OrderProcessor::class, 'handle'],
        $orderId
    );
    dispatch($processOrder);
    

Workflows

  • Avoid True Currying: This package only supports partial application (e.g., f(a)(b)), not multi-step currying (e.g., f(a)(b)(c)). Use react/partial for the latter.
  • Laravel-Specific Patterns:
    • Observers: Pre-bind model events.
      User::observe(new class {
          public function saved(User $user) {
              $log = Curry::apply([$this, 'logAction'], 'user_saved');
              $log($user->id);
          }
      });
      
    • Artisan Commands: Partialize repetitive logic.
      $command = new class extends Command {
          protected $signature = 'user:promote {id}';
          public function handle() {
              $promote = Curry::apply([User::class, 'promote'], $this->argument('id'));
              $promote();
          }
      };
      

Integration Tips

  • Combine with Laravel Helpers:
    $partial = Curry::apply([User::class, 'find'], 1);
    $user = $partial(); // Returns User or null
    
  • Type Safety: Use PHP 7.4+ return types with partials:
    $getUser = Curry::apply([User::class, 'find'], 1);
    $user = $getUser(); // IDE knows return type is User|null
    
  • Avoid Global State: Prefer dependency injection over partials for Laravel services:
    // Instead of:
    $partialLogger = Curry::apply([Logger::class, 'log'], 'error');
    
    // Use:
    $this->app->bind('logger', function () {
        return new Logger();
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning

    • The package emits deprecation notices. Migrate to react/partial immediately.
    • Example:
      // Old (react/curry)
      $partial = Curry::apply($func, $arg);
      
      // New (react/partial)
      $partial = \React\Partial\partial($func, $arg);
      
  2. Closure Scope Issues

    • Partially applied closures may lose $this context. Use static methods or bindTo:
      // Wrong (loses $this)
      $partial = Curry::apply([$this, 'method'], $arg);
      
      // Correct (binds $this)
      $partial = Curry::apply($this->method(...), $arg);
      
  3. Performance Overhead

    • Partial functions create closures. Cache frequently used partials:
      static $cachedPartial = null;
      if (!$cachedPartial) {
          $cachedPartial = Curry::apply($expensiveFunc, $arg);
      }
      
  4. Argument Order Matters

    • Partial application is left-to-right. Reorder arguments if needed:
      $concat = Curry::apply('str_concat', 'Prefix_');
      $result = $concat('suffix'); // "Prefix_suffix"
      
  5. Laravel-Specific Issues

    • Middleware: Partials may interfere with Laravel’s request lifecycle. Test thoroughly.
    • Queue Workers: Avoid blocking calls in partials (e.g., Model::first() in ReactPHP event loops).

Debugging

  • Inspect Partials:
    $partial = Curry::apply($func, $arg);
    var_dump($partial); // Should show "closure" with pre-bound args.
    
  • Check for Silent Failures:
    • Partials may swallow exceptions. Add error handling:
      try {
          $result = $partial();
      } catch (\Throwable $e) {
          Log::error("Partial failed: " . $e->getMessage());
      }
      
  • ReactPHP Deadlocks:
    • If using with ReactPHP, ensure partials don’t block the event loop:
      // Bad (blocks event loop)
      $partial = Curry::apply([DB::class, 'select'], 'users');
      
      // Good (async)
      $partial = Curry::apply([DB::class, 'selectOneFor'], $userId);
      

Tips

  1. Leverage react/partial Features

    • The replacement package supports currying and better error handling:
      use React\Partial\partial;
      
      $add = partial(fn($a, $b, $c) => $a + $b + $c, 1, 2);
      $result = $add(3); // 6
      
  2. Laravel Service Provider Helpers

    • Register partial helpers globally:
      $this->app->singleton('partial', function () {
          return new class {
              public function apply($func, ...$args) {
                  return Curry::apply($func, ...$args);
              }
          };
      });
      
  3. Testing Partials

    • Mock partials in PHPUnit:
      $partial = Curry::apply([$service, 'method'], $arg);
      $this->partialMock = $this->partialMock->method('__invoke')
          ->willReturn($expected);
      
  4. Avoid Overuse

    • Prefer Laravel’s dependency injection or closures for simple cases:
      // Instead of:
      $partial = Curry::apply([User::class, 'find'], 1);
      
      // Use:
      $user = User::find(1);
      
  5. Document Partial Usage

    • Clearly label partial functions in code to avoid confusion:
      /**
       * @var \Closure(int): User|null
       */
      $getUser = Curry::apply([User::class, 'find'], 1);
      

Extension Points

  • Custom Partial Logic Extend React\Curry\Curry for custom behavior:

    class CustomCurry extends \React\Curry\Curry {
        public static function apply($func, ...$args) {
            // Add validation or logging
            if (!is_callable($func)) {
                throw new \InvalidArgumentException('Function must be callable');
            }
            return parent::apply($func, ...$args);
        }
    }
    
  • Laravel Facade Create a facade for easier access:

    // app/Providers/AppServiceProvider.php
    use Illuminate\Support\Facades\Facade;
    
    Facade::register('Partial', function () {
        return new class {
            public function apply($func, ...$args) {
                return \React\Curry\Curry::apply($func, ...$args);
            }
        };
    });
    

    Usage:

    $partial = Partial::apply($func, $arg);
    
  • Integration with Laravel Events Create a trait for partial event listeners:

    trait PartialListener {
        protected function partialListener($event, $handler, ...$args) {
            return Curry::apply($handler, ...$args);
        }
    }
    

    Usage:

    Event::listen('user.created', $this->partialListener(
        'user.created',
        [$notifier, 'sendEmail'],
        'welcome
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky