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

Pheanstalk Bundle Laravel Package

drymek/pheanstalk-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    • Add dependencies via Composer (as per README) or manually clone into vendor/:
      composer require drymek/pheanstalk-bundle
      
    • Register the bundle in AppKernel.php (only for dev/test environments):
      $bundles[] = new drymek\PheanstalkBundle\drymekPheanstalkBundle();
      
    • Update app/autoload.php to register namespaces:
      $loader->registerNamespaces([
          'Pheanstalk' => __DIR__.'/../vendor/pheanstalk/classes',
          'drymek'    => __DIR__.'/../vendor/bundles',
      ]);
      
  2. Basic Configuration:

    • Configure in config.yml (defaults: 127.0.0.1:11300, 3s timeout):
      drymek_pheanstalk: ~
      
    • Override defaults if needed:
      drymek_pheanstalk:
          server: "your-beanstalkd-server"
          port: 11301
          timeout: 5
      
  3. First Use Case:

    • Inject the pheanstalk service into a controller/service:
      use Pheanstalk\Pheanstalk;
      
      class JobController extends Controller
      {
          public function enqueueJob(Pheanstalk $pheanstalk)
          {
              $tube = $pheanstalk->useTube('default');
              $tube->put('Hello, Beanstalk!');
              return new Response('Job enqueued!');
          }
      }
      

Implementation Patterns

Core Workflows

  1. Job Enqueuing:

    • Use Pheanstalk service to interact with Beanstalkd tubes:
      $pheanstalk->useTube('high_priority')->put('job_payload', 0, 60); // Priority 0, TTR 60s
      
    • Symfony Integration: Wrap in a service for reusability:
      services:
          app.job_enqueuer:
              class: App\Service\JobEnqueuer
              arguments: ['@pheanstalk']
      
  2. Job Consumption:

    • Reserve and process jobs in a worker script/service:
      $job = $pheanstalk->reserve(1); // Wait 1 second for a job
      if ($job) {
          $payload = $job->getData();
          // Process payload...
          $job->delete(); // Acknowledge completion
      }
      
    • Symfony Command: Create a console command for workers:
      class ProcessJobsCommand extends Command
      {
          protected function execute(InputInterface $input, OutputInterface $output)
          {
              $pheanstalk = $this->getContainer()->get('pheanstalk');
              while ($job = $pheanstalk->reserve()) {
                  // Process job...
                  $job->delete();
              }
          }
      }
      
  3. Tube Management:

    • Dynamically create/delete tubes:
      $pheanstalk->createTube('new_tube');
      $pheanstalk->deleteTube('old_tube');
      
    • Use Case: Route jobs by priority/type (e.g., emails, reports).
  4. Delayed Jobs:

    • Schedule jobs for later execution:
      $pheanstalk->useTube('delayed')->put('job_data', 0, time() + 3600); // Delay 1 hour
      

Integration Tips

  • Dependency Injection: Always inject Pheanstalk via constructor for testability.
  • Error Handling: Wrap Beanstalk operations in try-catch blocks:
    try {
        $job = $pheanstalk->reserve();
    } catch (\Pheanstalk\Exception\ConnectionException $e) {
        $this->logger->error('Beanstalkd connection failed');
    }
    
  • Configuration: Use environment variables for server/port (e.g., via parameters.yml):
    parameters:
        beanstalk.server: "%env(BEANSTALK_SERVER)%"
    
    drymek_pheanstalk:
        server: "%beanstalk.server%"
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • Default timeout (3s) may be too short for slow networks. Increase via config:
      drymek_pheanstalk:
          timeout: 10
      
    • Debugging: Check for ConnectionException if jobs hang indefinitely.
  2. Tube Naming:

    • Tube names are case-sensitive and must be alphanumeric/underscore.
    • Error: InvalidTubeNameException if invalid characters are used.
  3. Job Expiration:

    • Jobs with a time_to_run (TTR) exceeding the server’s max-job-timeout will fail.
    • Fix: Set TTR conservatively (e.g., 300 seconds).
  4. Development vs. Production:

    • The bundle is auto-loaded only in dev/test environments by default. Ensure it’s enabled in prod if needed:
      $bundles[] = new drymek\PheanstalkBundle\drymekPheanstalkBundle();
      
  5. Dev Tools Overhead:

    • The /_pheanstalk routes (for monitoring) are only available in dev/test. Avoid exposing them in production.

Debugging

  • Logs: Enable Symfony’s logger to track Beanstalk interactions:
    $this->logger->debug('Job reserved', ['job_id' => $job->getJobId()]);
    
  • Pheanstalk CLI: Use beanstalkd’s CLI tools (beanstalkd-console) to inspect tubes/jobs:
    beanstalkd-console -h 127.0.0.1 -p 11300
    
  • Common Issues:
    • Port Conflicts: Ensure Beanstalkd is running (beanstalkd -l 0.0.0.0 -p 11300).
    • Permission Denied: Verify the Symfony process has access to the Beanstalkd port.

Extension Points

  1. Custom Services:

    • Extend the bundle by creating a decorator for pheanstalk:
      services:
          app.pheanstalk.decorated:
              decorates: pheanstalk
              class: App\Service\PheanstalkDecorator
      
    • Use Case: Add retry logic or logging wrappers.
  2. Event Listeners:

    • Listen for job events (e.g., via Symfony’s event dispatcher) to trigger side effects:
      $pheanstalk->addListener('job.reserved', function ($job) {
          $this->dispatcher->dispatch(new JobReservedEvent($job));
      });
      
    • Note: The bundle doesn’t natively support events; use a decorator or proxy.
  3. Configuration Overrides:

    • Override bundle config via parameters or compiler passes:
      $container->setParameter('drymek_pheanstalk.server', getenv('BEANSTALK_HOST'));
      
  4. Testing:

    • Mock Pheanstalk in tests:
      $mock = $this->createMock(Pheanstalk::class);
      $mock->method('reserve')->willReturn($job);
      $this->container->set('pheanstalk', $mock);
      
    • Tip: Use pheanstalk-mock (e.g., php-pecl/pecl_http) for integration tests.
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.
terminal42/code-quality-tools
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