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

Php Resque Laravel Package

catch-of-the-day/php-resque

Redis-backed background job queue for PHP (Resque port). Enqueue jobs onto one or more prioritized queues and process them with distributed workers. Supports forking for leak resilience, failure handling, optional job status tracking, and setUp/tearDown hooks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require catch-of-the-day/php-resque
    

    Add require 'vendor/autoload.php'; to your project’s bootstrap file.

  2. First Job: Define a job class with a perform() method:

    class SendWelcomeEmail {
        public function perform() {
            // Your logic here
            echo "Email sent to: " . $this->args['email'];
        }
    }
    
  3. Enqueue a Job:

    Resque::setBackend('redis://localhost:6379');
    Resque::enqueue('emails', 'SendWelcomeEmail', ['email' => 'user@example.com']);
    
  4. Run a Worker:

    QUEUE=emails APP_INCLUDE=path/to/autoload.php php vendor/bin/resque
    

Implementation Patterns

Job Design

  • Modular Jobs: Split logic into small, single-purpose jobs (e.g., ProcessPayment, SendNotification).
  • Lifecycle Methods: Use setUp()/tearDown() for resource management (e.g., DB connections, logging).
    class ProcessPayment {
        public function setUp() {
            $this->logger = new Logger();
        }
        public function perform() {
            $this->logger->log("Processing payment...");
        }
        public function tearDown() {
            $this->logger->close();
        }
    }
    

Queue Management

  • Prioritize Queues: Start workers with high-priority queues first:
    QUEUE=critical,default,low php vendor/bin/resque
    
  • Dynamic Queues: Use environment variables to switch queues:
    QUEUE=${ENV_QUEUE} php vendor/bin/resque
    

Worker Scaling

  • Parallel Workers: Scale horizontally by running multiple workers:
    COUNT=4 QUEUE=emails php vendor/bin/resque
    
  • Monitoring: Use monit or systemd to manage worker processes.

Integration with Laravel

  • Service Providers: Register jobs in a service provider:
    public function boot() {
        Resque::setBackend(config('resque.redis'));
        Resque_Event::listen('beforeEnqueue', [$this, 'logJob']);
    }
    
  • Job Dispatching: Create a facade for cleaner syntax:
    class ResqueFacade extends \Illuminate\Support\Facades\Facade {
        protected static function getFacadeAccessor() { return 'resque'; }
    }
    

Event-Driven Workflows

  • Hooks: Extend functionality via events (e.g., retry failed jobs):
    Resque_Event::listen('onFailure', function($exception, $job) {
        if ($job->retries < 3) {
            Resque::enqueue($job->queue, get_class($job), $job->args, true, $job->retries + 1);
        }
    });
    

Gotchas and Tips

Common Pitfalls

  1. Redis Connection Issues:

    • Ensure Redis is running and accessible. Test with:
      $redis = new Redis();
      $redis->connect('localhost', 6379);
      
    • Use Resque::setBackend('tcp://user:pass@host:port') for authentication.
  2. Job Failures:

    • Uncaught exceptions in perform() mark jobs as failed. Use try-catch:
      public function perform() {
          try {
              // Risky logic
          } catch (\Exception $e) {
              throw new \RuntimeException("Failed: " . $e->getMessage());
          }
      }
      
  3. Worker Stuck on Jobs:

    • Long-running jobs may block workers. Use USR1 signal to kill stuck jobs:
      kill -USR1 <worker_pid>
      
  4. Autoloading Jobs:

    • Ensure job classes are autoloaded. For Composer, add to autoload.psr-4:
      {
          "autoload": {
              "psr-4": {
                  "App\\Jobs\\": "app/Jobs/"
              }
          }
      }
      

Debugging Tips

  • Verbose Logging: Enable detailed logs:
    VVERBOSE=1 QUEUE=emails php vendor/bin/resque
    
  • Job Inspection: Check Redis directly:
    redis-cli LRANGE resque:queue:emails 0 -1
    
  • Status Tracking: Use tokens to monitor jobs:
    $token = Resque::enqueue('emails', 'SendWelcomeEmail', ['email' => 'user@example.com'], true);
    $status = new Resque_Job_Status($token);
    echo $status->get(); // STATUS_WAITING, STATUS_RUNNING, etc.
    

Performance Optimization

  • Batch Processing: Process jobs in batches to reduce Redis overhead:
    Resque::enqueue('batch', 'ProcessBatch', ['ids' => [1, 2, 3]]);
    
  • Connection Pooling: Reuse Redis connections in workers:
    class My_Job {
        private static $redis;
        public function setUp() {
            self::$redis = new Redis();
            self::$redis->connect('localhost', 6379);
        }
        public function perform() {
            self::$redis->lPush('batch:ids', $this->args['id']);
        }
    }
    

Extension Points

  • Custom Backends: Extend Resque_Backend for non-Redis storage (e.g., database).
  • Job Serialization: Override serialization in Resque_Job for custom data formats.
  • Worker Plugins: Use the event system to add features (e.g., job metrics):
    Resque_Event::listen('afterPerform', function($job) {
        $metrics->record('job_completed', get_class($job));
    });
    

Laravel-Specific Quirks

  • Queue Configuration: Override defaults in config/resque.php:
    'redis' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'port' => env('REDIS_PORT', 6379),
        'password' => env('REDIS_PASSWORD', null),
    ],
    
  • Job Middleware: Use Laravel’s middleware pattern for cross-cutting concerns:
    class LogJobMiddleware {
        public function handle($job, Closure $next) {
            Log::info("Job started: " . get_class($job));
            $next($job);
            Log::info("Job completed: " . get_class($job));
        }
    }
    
    Register via Resque_Event::listen('beforePerform', [$middleware, 'handle']).
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony