bmonson
bmonson

Reputation: 45

How to pass global variable to Gearman worker (PHP)

My Gearman workers need to connect to my database. How can I pass a reference to my global $db variable? In the code below, $db is undefined in the executeJob function.

$db = new mysqli($db_host, $db_user, $db_pass, $db_name, $db_port);

// set up Gearman worker
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("execute", "executeJob");
while($worker->work());

function executeJob($job) {
    global $db;
    print_r($db); \\ UNDEFINED
}

The php manual suggests that context data can be passed when setting up the worker function with addFunction, but it's not clear to me if that's what I need or even how to do it. Thanks!!

Upvotes: 0

Views: 363

Answers (1)

Rene Korss
Rene Korss

Reputation: 5484

Yes, context data is what you need.

$db = new mysqli($db_host, $db_user, $db_pass, $db_name, $db_port);

// set up Gearman worker
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction("execute", "executeJob", $db);
while($worker->work());

function executeJob($job, $db) {
    print_r($db);
}

Upvotes: 1

Related Questions