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 Bundle Laravel Package

catch-of-the-day/php-resque-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

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

    Register the bundle in config/app.php under providers:

    CatchOfTheDay\ResqueBundle\ResqueServiceProvider::class,
    

    Publish the default configuration (optional):

    php artisan vendor:publish --provider="CatchOfTheDay\ResqueBundle\ResqueServiceProvider"
    
  2. Basic Configuration Edit config/resque.php to define your Redis connection and queue names:

    'connections' => [
        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],
    ],
    'queues' => [
        'default' => 'default_queue',
    ],
    
  3. First Job Create a job class (e.g., app/Jobs/ProcessUser.php):

    namespace App\Jobs;
    
    use CatchOfTheDay\ResqueBundle\Job\JobInterface;
    
    class ProcessUser implements JobInterface
    {
        public function perform($data)
        {
            // Your job logic here
            \Log::info('Processing user: ' . $data['user_id']);
        }
    }
    
  4. Enqueue a Job Dispatch the job in a controller or command:

    use CatchOfTheDay\ResqueBundle\Facades\Resque;
    
    Resque::enqueue('App\Jobs\ProcessUser', ['user_id' => 123]);
    
  5. Run the Worker Start the Resque worker in a terminal:

    php artisan resque:work default_queue
    

Implementation Patterns

Common Workflows

  1. Job Dispatching

    • From Controllers:
      Resque::enqueue('App\Jobs\SendEmail', [
          'to' => 'user@example.com',
          'subject' => 'Welcome!',
      ]);
      
    • From Commands:
      Resque::enqueueBulk([
          ['class' => 'App\Jobs\GenerateReport', 'args' => ['report_id' => 1]],
          ['class' => 'App\Jobs\GenerateReport', 'args' => ['report_id' => 2]],
      ]);
      
    • Delayed Jobs:
      Resque::enqueueIn(60, 'App\Jobs\CleanupTempFiles'); // Delay by 60 seconds
      
  2. Job Chaining Use after to chain jobs:

    Resque::enqueue('App\Jobs\ProcessOrder', ['order_id' => 1])
        ->after('App\Jobs\SendOrderConfirmation');
    
  3. Job Prioritization Assign priorities (lower number = higher priority):

    Resque::enqueue('App\Jobs\CriticalTask', [], 1); // Highest priority
    
  4. Worker Management

    • Multiple Workers: Run multiple workers for parallel processing:
      php artisan resque:work default_queue --workers=4
      
    • Queue-Specific Workers:
      php artisan resque:work high_priority_queue
      
  5. Job Retries Implement retry logic in your job:

    class ProcessPayment implements JobInterface
    {
        public function perform($data)
        {
            try {
                // Payment logic
            } catch (\Exception $e) {
                if ($this->shouldRetry($e)) {
                    Resque::requeue($this->getJobId(), 5); // Retry in 5 seconds
                }
            }
        }
    }
    

Integration Tips

  1. Laravel Events Trigger jobs from Laravel events:

    Event::listen('user.registered', function ($user) {
        Resque::enqueue('App\Jobs\WelcomeEmail', ['user' => $user]);
    });
    
  2. Database Transactions Combine with Laravel transactions for atomicity:

    DB::transaction(function () {
        // Save data
        Resque::enqueue('App\Jobs\PostProcessData', ['data_id' => $id]);
    });
    
  3. Monitoring Use Redis CLI to monitor queues:

    redis-cli --scan --pattern "*queues*" | grep -v "scan"
    
  4. Testing Mock jobs in tests:

    $this->partialMock(Resque::class, ['enqueue']);
    Resque::enqueue('App\Jobs\TestJob', []);
    $this->assertTrue(true); // Verify enqueue was called
    

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues

    • Ensure Redis is running and accessible.
    • Verify REDIS_HOST and REDIS_PORT in .env.
    • Use php artisan resque:status to check connection.
  2. Job Serialization

    • Only JSON-serializable data can be passed to jobs.
    • Avoid passing objects; use arrays or convert objects to arrays:
      Resque::enqueue('App\Jobs\ProcessUser', ['user' => $user->toArray()]);
      
  3. Worker Stuck on Jobs

    • Long-running jobs may block workers. Use Resque::timeout() to set a timeout:
      Resque::enqueue('App\Jobs\LongRunningTask', [], 300); // 5-minute timeout
      
    • Kill stuck workers gracefully:
      php artisan resque:kill default_queue
      
  4. Queue Locks

    • Resque uses Redis locks to prevent duplicate processing. If a job fails, the lock may persist.
    • Manually release locks if needed (use with caution):
      redis-cli DEL "resque:lock:job_class:job_id"
      
  5. Job Class Naming

    • Ensure job classes are fully namespaced (e.g., App\Jobs\ProcessUser).
    • Avoid dynamic class names unless absolutely necessary.

Debugging Tips

  1. Log Job Execution Add logging to your job’s perform method:

    \Log::debug('Job executed with data: ' . json_encode($data));
    
  2. Check Redis Directly Inspect queues and jobs:

    redis-cli LRANGE default_queue 0 -1  # List all jobs in the queue
    redis-cli HGETALL resque:job:job_id   # Inspect a specific job
    
  3. Worker Verbosity Run workers with -v for debug output:

    php artisan resque:work default_queue -v
    
  4. Job Failures Implement a failed method in your job to handle failures:

    public function failed(\Exception $e)
    {
        \Log::error('Job failed: ' . $e->getMessage());
        // Optionally send a notification
    }
    
  5. Environment-Specific Config Use .env for Redis settings:

    REDIS_HOST=redis.local
    REDIS_PORT=6379
    REDIS_DB=1
    

Extension Points

  1. Custom Job Classes Extend the base JobInterface for shared functionality:

    abstract class BaseJob implements JobInterface
    {
        protected $maxRetries = 3;
    
        public function shouldRetry(\Exception $e)
        {
            return $this->maxRetries-- > 0;
        }
    }
    
  2. Middleware for Jobs Create middleware to pre/post-process jobs:

    Resque::middleware(function ($job, $next) {
        \Log::info("Processing job: {$job->class}");
        return $next($job);
    });
    
  3. Custom Worker Classes Override the default worker behavior:

    php artisan make:resque-worker CustomWorker
    

    Then configure in config/resque.php:

    'worker_class' => \App\Resque\CustomWorker::class,
    
  4. Plugin System Extend the bundle by publishing and overriding views/templates (if any are included).

  5. Event Listeners Listen for Resque events (e.g., job enqueued, job started):

    Event::listen('resque.job.enqueued', function ($job) {
        \Log::info("Job enqueued: {$job->class}");
    });
    
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.
facebook/capi-param-builder-php
babelqueue/symfony
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