简体   繁体   English

如何在JSON响应中添加API在Lumen框架中响应所需的执行时间

[英]How to add execution time taken for an API to respond in Lumen framework in the JSON response

I would like to add the time taken by the API to respond in the response JSON. 我想添加API在响应JSON中响应所花费的时间。 Currently developing API with Lumen framework. 目前正在使用Lumen框架开发API。

If anyone can guide with best approach. 如果有人可以用最好的方法指导。 Not sure if I would have to use any Hooks provided by framework, or just calculate them in routes file. 不确定我是否必须使用框架提供的任何Hook,或者只是在路径文件中计算它们。 And how to push it to all the API responses. 以及如何将其推送到所有API响应。

PS: Still learning Laravel/Lumen framework. PS:还在学习Laravel / Lumen框架。

Thanks, Tanmay 谢谢,Tanmay

In your public/index.php file, add a constant there: 在你的public/index.php文件中,在那里添加一个常量:

<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| First we need to get an application instance. This creates an instance
| of the application / container and bootstraps the application so it
| is ready to receive HTTP / Console requests from the environment.
|
*/

// To calculate your app execution time
define('LUMEN_START', microtime(true));

$app = require __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$app->run();

The next step is create a middleware and enable it so we can manipulate our response. 下一步是创建一个中间件并启用它,以便我们可以操纵我们的响应。 Create a middleware in app/Http/Middleware with name MeasureExecutionTime.php . app/Http/Middleware创建一个名为MeasureExecutionTime.php app/Http/Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class MeasureExecutionTime
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Get the response
        $response = $next($request);

        // Calculate execution time
        $executionTime = microtime() - LUMEN_START;

        // I assume you're using valid json in your responses
        // Then I manipulate them below
        $content = json_decode($response->getContent(), true) + [
            'execution_time' => $executionTime,
        ];

        // Change the content of your response
        $response->setContent($content);

        // Return the response
        return $response;
    }
}

To enable this middleware in your application, add: 要在应用程序中启用此中间件,请添加:

$app->middleware([
   App\Http\Middleware\MeasureExecutionTime::class
]);

In your bootstrap/app.php file. 在您的bootstrap/app.php文件中。 So it would be like this: 所以它会是这样的:

<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    // n00p
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

// $app->withFacades();

// $app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

$app->middleware([
   App\Http\Middleware\MeasureExecutionTime::class
]);

// $app->middleware([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);

// $app->routeMiddleware([
//     'auth' => App\Http\Middleware\Authenticate::class,
// ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
// $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../app/Http/routes.php';
});

return $app;

Note If there are another middlewares in your application, you may add MeasureExecutionTime middleware at the END of any other middlewares. 注意如果应用程序中有其他中间件,您可以在任何其他中间件的END处添加MeasureExecutionTime中间件。

For further research I give you a link to documentation: 为了进一步研究,我给你一个文档链接:

  1. Middleware . 中间件
  2. Responses . 回应

UPDATE UPDATE

If you don't want to add elapsed time to your response body, you can add it to the headers: 如果您不想将经过的时间添加到响应正文中,可以将其添加到标题中:

<?php

namespace App\Http\Middleware;

use Closure;

class MeasureExecutionTime
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->headers->set('X-Elapsed-Time', microtime(true) - LUMEN_START);

        return $response;
    }
}

In directory public you have file index.php . 在目录public您有文件index.php Create there a variable: 在那里创建一个变量:

define('LUMEN_START', microtime());

Now in your controller, you can just pass a parameter: 现在在您的控制器中,您只需传递一个参数:

return [
    'response_time' => microtime() - LUMEN_START
];

It will be measuring time from start ( public/index.php is the first file run by server) to the response. 它将测量从开始( public/index.php是服务器运行的第一个文件)到响应的时间。

I use Lumen 5.3 and want to return JsonResponse . 我使用Lumen 5.3并希望返回JsonResponse Because of this I had to modify the middleware solution from Alfa a little bit: 因此,我不得不稍微修改一下Alfa的中间件解决方案:

Instead of 代替

// Change the content of your response
$response->setContent($content);

I use 我用

// Change the content of your response
$response->setData($content);

Not sure if this is related to JsonResponse or the Laravel/Lumen version but it works for me. 不确定这是否与JsonResponse或Laravel / Lumen版本有关,但它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM