这里有一个奇怪的人。我刚刚完成了一个Silex应用程序,但是在获取$ app->完成触发时遇到了问题。这是我的代码:
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/', function (Request $request) {
$batchProcess = function () {
long_process();
};
$app->finish($batchProcess);
return $app->json("ok", 200);
};
$app->run();
所以这就是问题:批处理过程永远不会运行!试图找到错误,我在一个Silex \ Application中的“on”函数中添加了一个var_export:
/**
* Adds an event listener that listens on the specified events.
*
* @param string $eventName The event to listen on
* @param callable $callback The listener
* @param integer $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function on($eventName, $callback, $priority = 0)
{
$this['dispatcher'] = $this->share($this->extend('dispatcher', function ($dispatcher, $app) use ($callback, $priority, $eventName) {
$dispatcher->addListener($eventName, $callback, $priority);
return $dispatcher;
}));
var_export($this['dispatcher']);
}
当var_export在那里时,一切正常(尽管内核在发送任何数据之前运行批处理)。当var_export被注释掉时,“ok”会立即返回,批处理过程永远不会运行。
我做错了什么?为什么内核在没有执行我的进程的情况下终止?
答案 0 :(得分:0)
通过对Response的两次更改,可能有一种方法可以实现它 类。
- 第一个是在
ob_flush()
flush()
之前添加Response::send()
。- 第二个是设置
content-length
标题。
我能够在不修改Response
类的情况下实现相同的效果。首先,您需要移动在finish
方法之外的get
中间件中设置的回调,并手动检查路由(在这种情况下'GET_'
响应'/'
路径) :
$app->finish(function() {
if ('GET_' === $request->attributes->get('_route')) {
long_process();
}
});
然后,这是get
方法的样子:
$app->get('/', function(Request $request) use ($app) {
$content = json_encode(array(
'status' => 'ok',
));
$response = new Response($content, 200);
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('Content-Length', strlen($content));
$response->send();
ob_flush();
return $response;
});
设置内容长度非常重要,或者JSON内容将被发送两次,因为在方法中返回$ response,并由Silex发送。