0

ここで奇妙なものを手に入れました。私は Silex アプリをほぼ使い果たしましたが、 $app->finish をトリガーするのに問題があります。これが私のコードです:

<?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」がすぐに返され、バッチ プロセスは実行されません。

私は何を間違っていますか?プロセスを実行せずにカーネルが終了するのはなぜですか?

4

1 に答える 1

0

Igor Wiedler のコメントを参照してください。

Response クラスに 2 つの変更を加えることで、それを達成する方法があるかもしれません。

  • 1 つ目はinのob_flush()前に追加することです。flush()Response::send()
  • content-length2 つ目は、ヘッダーの設定です。

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;
});

content-length の設定は非常に重要です。そうしないと、$response がメソッドで返され、Silex によって送信されるため、JSON コンテンツが 2 回送信されます。

于 2013-08-16T08:37:13.163 に答える