How do I Access my Models using a Daemon in Zend F

2019-04-11 14:37发布

I am working on a project that is using Phirehose to collect and consume the Twitter Streaming API. The Phirehose library is designed to be run from the command line, preferably as a daemon or cron job.

I created a daemon and placed it in the library folder. Bootstrap.php has been updated to autoload the custom library. So, the application itself has no problem seeing my daemon.

My issue is how to integrate it properly with Zend Framework. I need to be able to call the daemon file directly to start it from the command line or using a tool such as Upstart, but in doing so the Zend application doesn't load which means I don't have access to my models.

I could create a controller to start it, but I don't want to add the security issue of somebody being able to control the daemon from a web interface. I could also write the PDO to manually connect to the database, but I'm trying to avoid it for scaling reasons. I'd prefer all database connection data reside in application.ini.

Is there a way, within my daemon class, to initialize my Zend Framework application so I can use the models?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-11 14:57

This example demonstrates how I perform background tasks using Zend_Queue. In this particular example I'm generating invoices in background using Zend_Queue and cronjob, my Zend_Queue is initialised and registered in bootstrap.

Creating a job, My_Job source is here:

class My_Job_SendInvoice extends My_Job
{
    protected $_invoiceId = null;

    public function __construct(Zend_Queue $queue, array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }

        parent::__construct($queue);
    }

    public function job()
    {
        $filename = InvoiceTable::getInstance()
            ->generateInvoice($this->_invoiceId);

        return is_file($filename);
    }
}

Registering job, somewhere inside your service or model:

$backgroundJob = new My_Job_SendInvoice(Zend_Registry::get('queue'), array(
    'invoiceId' => $invoiceId
));
$backgroundJob->execute();

Creating background script:

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/..'));

// temp, environment should be specified prior execution
define('APPLICATION_ENV', 'development');

set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));


require_once 'Zend/Application.php';

$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->bootstrap();

/* @var $queue Zend_Queue */
$queue    = Zend_Registry::get('queue');
$messages = $queue->receive(5);

foreach ($messages as $i => $message) {
    /* @var $job My_Job */
    $job = unserialize($message->body);
    if ($job->job()) {
        $queue->deleteMessage($message);
    }
}
查看更多
登录 后发表回答