Skip to content

Instantly share code, notes, and snippets.

@omerucel
Created August 3, 2016 08:01
Show Gist options
  • Save omerucel/485e6fcfc74ce50264c14ecc9579d3cd to your computer and use it in GitHub Desktop.
Save omerucel/485e6fcfc74ce50264c14ecc9579d3cd to your computer and use it in GitHub Desktop.
gearman worker
<?php
namespace Gearman;
class EventConsumer extends WorkerAbstract
{
/**
* @var string
*/
protected $token;
/**
* @var array
*/
protected $events = array();
public function run()
{
$this->getGearmanWorker()->addFunction('handle_event', array($this, 'handleEvent'));
parent::run();
}
public function handleEvent(\GearmanJob $job)
{
try {
$this->tryHandleEvent($job);
} catch (\Exception $exception) {
$this->getLogger()->emergency($exception);
}
}
/**
* @param \GearmanJob $job
*/
protected function tryHandleEvent(\GearmanJob $job)
{
$workload = json_encode($job->workload());
}
}
<?php
namespace Gearman;
use OU\DI;
use Psr\Log\LoggerInterface;
abstract class WorkerAbstract
{
/**
* @var DI
*/
protected $di;
/**
* @var \GearmanWorker
*/
protected $gearmanWorker;
/**
* @param DI $di
*/
public function __construct(DI $di)
{
$this->di = $di;
}
public function run()
{
while ($this->getGearmanWorker()->work()) {
$this->logGearmanErrorIfExists();
};
$this->logGearmanErrorIfExists();
}
protected function logGearmanErrorIfExists()
{
if ($this->getGearmanWorker()->returnCode() != GEARMAN_SUCCESS) {
$this->getLogger()->error(
'GearmanStatus: ' . $this->getGearmanWorker()->returnCode()
. ' GearmanError: ' . $this->getGearmanWorker()->error()
);
}
}
/**
* @return \GearmanWorker
*/
protected function getGearmanWorker()
{
if ($this->gearmanWorker == null) {
$this->gearmanWorker = new \GearmanWorker();
$this->gearmanWorker->addServers(strval($this->getConfig()->gearman->servers));
}
return $this->gearmanWorker;
}
/**
* @return \stdClass
* @throws \Exception
*/
protected function getConfig()
{
return $this->getDi()->get('config');
}
/**
* @return LoggerInterface
* @throws \Exception
*/
protected function getLogger()
{
return $this->getDi()->get('logger_helper')->getLogger();
}
/**
* @return DI
*/
public function getDi()
{
return $this->di;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment