我正在开发一个使用 Phirehose 来收集和使用 Twitter Streaming API 的项目。 Phirehose 库旨在从命令行运行,最好作为守护程序或 cron 作业运行。
我创建了一个守护进程并将其放在库文件夹中。 Bootstrap.php 已更新为自动加载自定义库。因此,应用程序本身在查看我的守护程序时没有问题。
我的问题是如何将它与 Zend Framework 正确集成。我需要能够直接调用守护程序文件以从命令行或使用诸如 Upstart 之类的工具启动它,但这样做时 Zend 应用程序不会加载,这意味着我无法访问我的模型。
我可以创建一个 Controller 来启动它,但我不想添加某人能够从 Web 界面控制守护程序的安全问题。我也可以编写 PDO 来手动连接到数据库,但出于扩展的原因我试图避免它。我希望所有数据库连接数据都驻留在 application.ini 中。
有没有办法在我的守护程序类中初始化我的 Zend Framework 应用程序,以便我可以使用这些模型?
最佳答案
这个例子演示了我如何使用 Zend_Queue 执行后台任务。
在这个特定的例子中,我使用 Zend_Queue 和 cronjob 在后台生成发票,我的 Zend_Queue 被初始化并在 bootstrap 中注册。
创建作业,My_Job 源是 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);
}
}
在您的服务或模型中的某处注册作业:
$backgroundJob = new My_Job_SendInvoice(Zend_Registry::get('queue'), array(
'invoiceId' => $invoiceId
));
$backgroundJob->execute();
创建后台脚本:
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);
}
}
关于php - 如何使用 Zend Framework 中的守护程序访问我的模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10954616/