In our last post, we have seen how we can easily setup Gearman to process background tasks. In this post, we shall see code samples of worker and client in PHP.

Let’s start with the worker script first. The worker defines a function and registers it to gearman. Then it goes into an infinite loop waiting for workloads.

// Create a GearmanWorker object
$worker= new GearmanWorker();
// Add the default server
// Register the processing function
$worker->addFunction("process_string", "processString");
// Trigger the infinite loop
while ($worker->work());
// The main function that processes the job
function processString($job)
  // get the workload - it's a string. use serialization to pass objects
  $param = $job->workload();
  return "You passed the string: {$param} \n It had: ".strlen($param)." chars \n";

The client is pretty straightforward. It calls a registered function and passes a parameter as string.

// construct a client object
$client= new GearmanClient();
// add the default server
// print the output of the job. first parameter is the job name, second one is the parameter
print $client->do("process_string", "Hello Gearman!");

The output:

Isn’t that straight and simple?