PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Using Gearman from PHP

Note: This article was originally published at Planet PHP on 16 February 2011.
Planet PHP
I've introduced Gearman into a project I'm working on, and since a few people have asked I thought I'd share my experiences. Basically, this application generates some PDFs from a variety of data sources, makes images, and emails it. Since the whole data processing, image handling, PDF generation process is fairly heavy, I'm putting the requests to generate these onto a gearman queue and having some workers process the jobs. The eventual aim is to bring up EC2 instances (or php-specific cloud hosting perhaps? Recommendations gratefully received!) to do this work but right now I have one worker and it's all on one server.

I installed Gearman and the pecl module for it, and then looked at how to integrate it into my application. I was replacing an existing synchronous script that generated the output, so I already had the code I wanted to be performed by the worker, and since this was a ZF application I set up a CLI bootstrap for it and ran my existing functionality from a controller called that way.

Adding Jobs to Gearman


Adding jobs to the gearman queue was easy, but I struggled to understand which function I needed from the documentation. It turns out that if you just want a job to wait for some resource to be available to do it, then Gearman_Client::doBackground() is the way forward. My code to add jobs looks like this:

$client = new Gearman_Client();
$client-addServers('127.0.0.1');
$client-doBackground('basicReport', json_encode($job_data));
A
The $job_data variable holds an array of data that is needed by the worker to know what to generate.

Writing a Gearman Worker in PHP


As I say, I bootstrapped my ZF application from the commandline and created a controller action to be called. It contains code like this:

A A A A $worker = new GearmanWorker();
A A A A $worker-addServer('127.0.0.1');
A A A A $worker-addFunction('basicReport', [callback]);
A A A A while ($worker-work()) {
A A A A A A echo "working ... \n";ob_flush()"/

Truncated by Planet PHP, read more at the original (another 2680 bytes)