[英]Is there a way to pass a callback as data parameter to Laravel 4.2 Queue::push()
我有一些耗时的代码来处理我想在后台运行的一系列HTTP请求的结果。 我正在使用Redis存储来管理队列。 这是我尝试过的:
Queue::push( 'FetchUrls', [
'urls' => [ 'http://one.com', 'http://two.com', 'http://three.com' ],
'complete' => function( $response ) { /* process data returned by URL here */ },
'error' => function( $error ) { /* process HTTP errors here */ },
]);
Redis队列存储中显示的是$data
参数的JSON
序列化:
{
"job": "FetchUrls",
"data": {
"urls": [
"http:\/\/one.com",
"http:\/\/two.com",
"http:\/\/three.com"
],
"complete": [],
"error": []
},
"id": "aAlkNM0ySLXcczlLYho19TlWYs9hStzl",
"attempts": 1
}
如您所见,回调仅在队列存储中显示为空数组。 我以前从未使用过Queue类,因此我可能会以错误的方式解决此问题。 我正在寻找解决此问题的最佳方法的建议。 谢谢!
为了安全起见,您应该仅推送数组(因为序列化存在问题)。
要回答您的问题- 没有解决方法 ,您应该重新考虑逻辑。
您可以传递函数名称,并使用诸如call_user_func()
类的函数来调用它们。
Queue::push('FetchUrls', [
'urls' => ['http://one.com', 'http://two.com', 'http://three.com'],
'complete' => ['ResponseHandler', 'fetchComplete'],
'error' => ['ResponseHandler', 'fetchError'],
]);
class FetchUrls
{
public function fire($job, $data)
{
list($urls, $complete, $error) = $data;
foreach ($urls as $url) {
if ($response = $this->fetch($url)) {
$job->delete();
call_user_func($complete, $response);
} else {
$job->release();
call_user_func($error, $this->getError());
}
}
}
private function fetch($url)
{
// ...
}
private function getError()
{
// ...
}
}
class ResponseHandler
{
public static function fetchComplete($response)
{
// ...
}
public static function fetchError($error)
{
// ...
}
}
这种方法有一个非基于类的版本,但这是相对干净的。
以['ResponseHandler', 'fetchComplete']
作为第一个参数的call_user_func()
将调用ResponseHandler::fetchComplete()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.