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

mjphaynes/php-resque

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mjphaynes/php-resque
    

    Ensure Redis is running locally or configured in your environment.

  2. Basic Job Definition Create a job class extending Resque\Job:

    namespace App\Jobs;
    
    use Resque\Job;
    
    class SendEmailJob extends Job
    {
        protected $email;
        protected $message;
    
        public function __construct($email, $message)
        {
            $this->email = $email;
            $this->message = $message;
        }
    
        public function perform()
        {
            // Your logic here (e.g., send email via Laravel Mailer)
            \Log::info("Sending email to {$this->email}: {$this->message}");
        }
    }
    
  3. Enqueue a Job

    use App\Jobs\SendEmailJob;
    
    $job = new SendEmailJob('user@example.com', 'Hello!');
    $job->enqueue('emails'); // 'emails' is the queue name
    
  4. Run the Worker

    php artisan resque:work emails
    

    (Ensure php artisan resque:setup is run first to configure Redis.)


First Use Case: Background Email Processing

  • Problem: Sending emails synchronously slows down your web requests.
  • Solution: Offload email sending to a background job.
  • Workflow:
    1. User submits a form → trigger SendEmailJob.
    2. Worker processes the job asynchronously.
    3. User gets a response immediately while the email is sent later.

Implementation Patterns

Workflow: Job Lifecycle

  1. Enqueueing

    $job = new ProcessOrderJob($orderId);
    $job->enqueue('orders', [], $delay = 60); // Delay in seconds
    
    • Use named queues (orders, high_priority) for organization.
    • Leverage delays for time-sensitive tasks (e.g., "send reminder in 1 hour").
  2. Processing

    • Workers pull jobs from Redis and execute perform().
    • Use Resque::work(1) for single-process workers or Resque::work($numProcesses) for parallelism.
  3. Retrying Failed Jobs

    class ProcessPaymentJob extends Job
    {
        public function perform()
        {
            try {
                // Payment logic
            } catch (\Exception $e) {
                $this->fail($e); // Marks job as failed (retryable)
            }
        }
    }
    
    • Failed jobs are requeued automatically (configurable retry limits in config/resque.php).
  4. Monitoring

    • Use Resque::queues() to list all queues.
    • Check job status with Resque::size('queue_name').
    • Integrate with Laravel Horizon for a dashboard (if using Laravel).

Integration Tips

  1. Laravel Integration

    • Use php-resque alongside Laravel’s queue system by wrapping jobs in Resque\Job:
      class LaravelJobAdapter extends Job
      {
          protected $laravelJob;
      
          public function __construct($laravelJob)
          {
              $this->laravelJob = $laravelJob;
          }
      
          public function perform()
          {
              $this->laravelJob->handle();
          }
      }
      
    • Dispatch Laravel jobs to Resque:
      $laravelJob = new \App\Jobs\SendNotification;
      $resqueJob = new LaravelJobAdapter($laravelJob);
      $resqueJob->enqueue('notifications');
      
  2. Dynamic Queues

    • Route jobs dynamically based on conditions:
      $queue = $user->isPremium() ? 'premium' : 'standard';
      $job->enqueue($queue);
      
  3. Priority Queues

    • Use multiple queues (e.g., high, medium, low) and prioritize workers:
      php artisan resque:work high --size=2  # 2 workers for high-priority queue
      
  4. Job Chaining

    • Chain jobs sequentially:
      $job1 = new ProcessDataJob($data);
      $job1->enqueue('data_processing');
      
      $job2 = new AnalyzeDataJob($data);
      $job2->enqueue('analysis', [], 30); // After $job1 completes
      

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues

    • Ensure Redis is accessible and the config (config/resque.php) matches your environment.
    • Common error: Connection refused → Verify Redis server is running (redis-cli ping).
  2. Job Stuck in Queue

    • If jobs aren’t processing, check:
      • Worker logs (php artisan resque:work --verbose).
      • Redis memory limits (redis-cli info memory).
      • Worker crashes (use supervisord or pm2 for process management).
  3. Serialization Problems

    • Avoid complex objects in job constructors. Use primitive data types or JSON-serializable arrays.
    • Example of a bad job:
      class BadJob extends Job {
          public function __construct(User $user) { // User may not be serializable
              $this->user = $user;
          }
      }
      
    • Fix: Pass the user’s ID and fetch later:
      class GoodJob extends Job {
          public function __construct(int $userId) {
              $this->userId = $userId;
          }
      }
      
  4. Worker Timeout

    • Default timeout is 30 seconds. Increase for long-running jobs:
      $job->enqueue('long_running', [], 0, 300); // 5-minute timeout
      

Debugging

  1. Log Worker Output

    • Redirect worker logs to a file:
      php artisan resque:work queue_name --log-file=/path/to/worker.log
      
    • Use Laravel’s logging inside perform():
      \Log::debug("Job data: " . json_encode($this->data));
      
  2. Inspect Queues

    • List all jobs in a queue:
      php artisan resque:list queue_name
      
    • Remove a stuck job:
      php artisan resque:remove queue_name job_id
      
  3. Test Locally with Docker

    • Use a Redis container:
      docker run -p 6379:6379 redis
      
    • Configure config/resque.php to point to redis://localhost.

Tips

  1. Environment-Specific Config

    • Override Redis settings per environment:
      // config/resque.php
      'connection' => env('REDIS_URL', 'redis://localhost'),
      
  2. Custom Job Classes

    • Extend Resque\Job for shared functionality:
      abstract class BaseJob extends Job
      {
          protected $retryCount = 0;
      
          public function fail(\Exception $e)
          {
              $this->retryCount++;
              if ($this->retryCount < 3) {
                  parent::fail($e);
              }
          }
      }
      
  3. Rate Limiting

    • Throttle jobs to avoid Redis overload:
      $job->enqueue('throttled', [], 0, 0, 10); // Max 10 concurrent jobs
      
  4. Plugins

    • Use resque-scheduler for cron-like job scheduling:
      composer require mjphaynes/resque-scheduler
      
    • Schedule a job to run daily at 2 AM:
      $job = new DailyReportJob();
      $job->schedule('0 2 * * *');
      $job->save();
      
  5. Performance

    • Batch small jobs:
      $batch = new BatchJob([$job1, $job2, $job3]);
      $batch->enqueue('batch_processing');
      
    • Use Resque::work($numProcesses) to parallelize workloads.
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php