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

拜拜、爱过 提交于 2019-12-04 13:23:16

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!