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

Job Server Bundle Laravel Package

abc/job-server-bundle

Symfony bundle for asynchronous distributed job processing via php-enqueue. Supports jobs, batches, sequences, free composition, status tracking, cancellation/restart, cron jobs (with AbcSchedulerBundle), plus a JSON REST API, PHP client, and OpenAPI docs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require abc/job-server-bundle
    

    Ensure EnqueueBundle is installed and configured with a transport (e.g., Redis, RabbitMQ, or Doctrine).

  2. Configure the Bundle Update config/packages/abc_job_server.yaml:

    abc_job_server:
        transport: default  # or your custom transport name
        api:
            enabled: true   # Enable REST API if needed
    
  3. Set Up Database Run migrations to create job-related tables:

    bin/console doctrine:migrations:diff
    bin/console doctrine:migrations:migrate
    
  4. First Job Dispatch Define a job class (e.g., src/Job/MyJob.php):

    namespace App\Job;
    
    use Abc\JobServerBundle\Job\JobInterface;
    
    class MyJob implements JobInterface {
        public function run(): void {
            // Your job logic here
        }
    }
    

    Dispatch it via CLI or controller:

    bin/console abc:job:dispatch App\Job\MyJob
    
  5. Verify Job Status Check job status via API (/api/jobs/{id}) or CLI:

    bin/console abc:job:status <job-id>
    

Implementation Patterns

Core Workflows

1. Job Dispatching

  • CLI Dispatch:
    bin/console abc:job:dispatch App\Job\MyJob --param=value
    
  • Programmatic Dispatch (e.g., in a controller):
    use Abc\JobServerBundle\Job\JobDispatcher;
    
    $dispatcher = $container->get(JobDispatcher::class);
    $dispatcher->dispatch(new MyJob($param));
    

2. Job Composition

  • Sequences (run jobs in order):
    use Abc\JobServerBundle\Job\Sequence;
    
    $sequence = new Sequence();
    $sequence->addJob(new JobA());
    $sequence->addJob(new JobB());
    $dispatcher->dispatch($sequence);
    
  • Batches (run jobs in parallel):
    use Abc\JobServerBundle\Job\Batch;
    
    $batch = new Batch();
    $batch->addJob(new JobX());
    $batch->addJob(new JobY());
    $dispatcher->dispatch($batch);
    

3. Job Monitoring

  • API Endpoints:
    • GET /api/jobs → List jobs.
    • GET /api/jobs/{id} → Job details.
    • POST /api/jobs/{id}/cancel → Cancel a job.
  • CLI Commands:
    bin/console abc:job:list          # List all jobs
    bin/console abc:job:status <id>   # Check job status
    bin/console abc:job:cancel <id>   # Cancel a job
    

4. Cron Jobs (with AbcSchedulerBundle)

  • Configure cron jobs in config/packages/abc_scheduler.yaml:
    abc_scheduler:
        jobs:
            my_cron_job:
                class: App\Job\MyCronJob
                schedule: "0 0 * * *"  # Run daily at midnight
    

Integration Tips

  • Dependency Injection: Inject JobDispatcher or JobRepository into services for seamless job handling.
  • Event Listeners: Extend functionality by listening to job events (e.g., JobStartedEvent, JobFailedEvent):
    use Abc\JobServerBundle\Event\JobEvent;
    
    $eventDispatcher->addListener(JobEvent::JOB_STARTED, function (JobEvent $event) {
        // Log or notify when a job starts
    });
    
  • Custom Job States: Extend the JobState enum or create custom states by implementing JobInterface.

Gotchas and Tips

Pitfalls

  1. Transport Configuration Mismatch

    • Ensure the abc_job_server.transport setting matches your enqueue transport configuration.
    • Debug: Check bin/console debug:container abc_job_server.transport to verify the active transport.
  2. Database Schema Updates

    • Always run migrations after bundle updates to avoid schema drift:
      bin/console doctrine:migrations:diff
      bin/console doctrine:migrations:migrate
      
  3. Job Serialization Issues

    • Jobs must be serializable. Avoid circular references or non-serializable dependencies (e.g., Doctrine entities without proper handling).
    • Fix: Implement __serialize() and __unserialize() in custom jobs or use #[AsArray] for DTOs.
  4. API Authentication

    • The REST API is unauthenticated by default. Secure it with Symfony’s security layer or API tokens:
      # config/packages/security.yaml
      firewalls:
          api:
              pattern: ^/api/jobs
              stateless: true
              json_login:
                  check_path: /api/login
      
  5. Worker Management

    • Workers must be running to process jobs. Start them via:
      bin/console enqueue:consume --transport=default
      
    • Tip: Use a process manager (e.g., Supervisor) to keep workers alive.

Debugging

  • Job Stuck in Queue?

    • Check the transport (e.g., Redis CLI or RabbitMQ management UI) for stuck messages.
    • Restart workers or manually trigger reprocessing:
      bin/console abc:job:retry <job-id>
      
  • Job Fails Silently?

    • Enable debug logging in config/packages/monolog.yaml:
      handlers:
          job_server:
              type: stream
              path: "%kernel.logs_dir%/%kernel.environment%.job-server.log"
              level: debug
              channels: ["abc_job_server"]
      
  • API Returns 500 Errors?

    • Validate OpenAPI specs (/api/doc) and check for missing dependencies (e.g., AbcSchedulerBundle for cron jobs).

Extension Points

  1. Custom Job States Extend the JobState enum or create a custom state machine by implementing JobStateProviderInterface.

  2. Transport-Specific Logic Override the JobTransport service to customize message handling (e.g., for SNS/SQS).

  3. Job Metadata Add custom metadata to jobs via the setMetadata() method:

    $job = new MyJob();
    $job->setMetadata(['priority' => 'high']);
    
  4. Event-Driven Extensions Listen to events like JobFailedEvent to trigger alerts or retries:

    $eventDispatcher->addListener(JobEvent::JOB_FAILED, function (JobFailedEvent $event) {
        // Send Slack notification or log to Sentry
    });
    
  5. Testing Jobs Use the JobTestCase base class or mock the JobDispatcher in PHPUnit:

    $dispatcher = $this->createMock(JobDispatcher::class);
    $dispatcher->expects($this->once())->method('dispatch');
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
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