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

david-garcia/php-resque

PHP port of GitHub’s Resque: a Redis-backed background job system for enqueueing and processing jobs with distributed workers. Supports multiple queues/priorities, forking for memory-leak resilience, job status tracking, failure marking, and setUp/tearDown hooks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require david-garcia/php-resque
    

    Ensure Redis is running locally or on your server (redis-server).

  2. Basic Job Definition: Create a class implementing Resque_Job:

    class ExampleJob implements Resque_Job {
        public function perform($arg1, $arg2 = null) {
            // Job logic here
            return "Processed: {$arg1}";
        }
    }
    
  3. Enqueue a Job:

    $queue = new Resque_Queue('default');
    $queue->enqueue('ExampleJob', ['param1', 'param2']);
    
  4. Run a Worker:

    php vendor/bin/resque-worker default
    

    Replace default with your queue name.

First Use Case

Use this package to offload time-consuming tasks (e.g., sending emails, processing images) to background jobs. For example:

// In a controller or command
$queue = new Resque_Queue('emails');
$queue->enqueue('EmailJob', ['user@example.com', 'Welcome!']);

// Later, run the worker in the background

Implementation Patterns

Workflows

  1. Job Chaining: Enqueue jobs sequentially or in parallel by leveraging Redis lists:

    $queue = new Resque_Queue('processing');
    $queue->enqueue('JobA', ['data']);
    $queue->enqueue('JobB', ['data']); // Runs after JobA
    
  2. Priority Queues: Use named queues for priority handling:

    $highPriorityQueue = new Resque_Queue('high');
    $highPriorityQueue->enqueue('CriticalJob', ['urgent_data']);
    
  3. Worker Distribution: Run multiple workers on different machines/processes to distribute load:

    # Terminal 1
    php vendor/bin/resque-worker default
    
    # Terminal 2 (on another machine)
    php vendor/bin/resque-worker default
    
  4. Setup/TearDown: Override setUp() and tearDown() in your job class for pre/post job logic:

    class DatabaseJob implements Resque_Job {
        public function setUp() {
            $this->db = new DatabaseConnection();
        }
    
        public function perform($query) {
            $this->db->query($query);
        }
    
        public function tearDown() {
            $this->db->disconnect();
        }
    }
    

Integration Tips

  • Laravel Integration: Use Laravel’s service container to bind jobs:

    $app->bind('ExampleJob', function() {
        return new ExampleJob();
    });
    

    Enqueue jobs from controllers/commands:

    $queue = new Resque_Queue('laravel');
    $queue->enqueue('ExampleJob', ['data']);
    
  • Error Handling: Implement onFailure() in your job to handle failures gracefully:

    public function onFailure($exception) {
        Log::error("Job failed: " . $exception->getMessage());
    }
    
  • Testing: Use Redis’ FLUSHDB to reset queues between tests. Mock jobs in unit tests:

    $job = $this->getMockBuilder('ExampleJob')->getMock();
    $job->expects($this->once())->method('perform');
    

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues:

    • Ensure Redis is accessible and the host/port in config.php (if used) are correct.
    • Debug with redis-cli PING to verify connectivity.
  2. Job Serialization:

    • Only JSON-serializable data can be passed to jobs. Avoid passing objects directly; use arrays or implement JsonSerializable.
  3. Worker Crashes:

    • Workers fork processes, so ensure your job logic is stateless and doesn’t rely on global variables.
    • If a worker crashes, Redis will retry the job (configurable via retry option in enqueue).
  4. Queue Stuck Jobs:

    • Jobs may get stuck if they enter an infinite loop or block indefinitely. Use timeouts or implement tearDown to clean up resources.
  5. No Web Interface:

    • Unlike the Ruby version, this fork lacks a built-in web UI. Use Redis tools like redis-cli or third-party tools (e.g., RedisInsight) to monitor queues.

Debugging

  • Log Worker Output: Redirect worker output to a file for debugging:

    php vendor/bin/resque-worker default > worker.log 2>&1 &
    
  • Check Job Status: Use Redis commands to inspect queues:

    redis-cli LRANGE resque:queue:default 0 -1  # List all jobs in the queue
    redis-cli HGETALL resque:job:queue:default:123  # Inspect a specific job
    
  • Enable Verbose Mode: Pass -v to the worker for detailed logs:

    php vendor/bin/resque-worker -v default
    

Tips

  1. Custom Configurations: Override default settings (e.g., retry delay, timeout) by extending Resque_Worker:

    class CustomWorker extends Resque_Worker {
        protected $timeout = 300; // 5 minutes
    }
    
  2. Job Retries: Configure retry logic in enqueue:

    $queue->enqueue('Job', ['data'], ['retry' => 3, 'retry_delay' => 60]);
    
  3. Environment Awareness: Use different queues for development/staging/production to avoid mixing jobs:

    $queueName = config('app.env') === 'production' ? 'prod' : 'dev';
    $queue = new Resque_Queue($queueName);
    
  4. Monitoring: Track job progress by logging to Redis:

    public function perform($data) {
        Redis::set("job:progress:{$this->getJobId()}", 'in_progress');
        // Job logic
        Redis::del("job:progress:{$this->getJobId()}");
    }
    
  5. Forking Limitations: Avoid heavy operations in setUp/tearDown as they run in the parent process. Offload such logic to the job’s perform method or use Laravel’s service container for shared resources.

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.
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
spatie/mailcoach-vapor