【发布时间】:2016-12-25 02:24:49
【问题描述】:
我正在为我的应用程序使用 slim 框架 3。
我需要关于如何实现为每个请求生成唯一 ID 或请求 ID,然后在响应中显示该唯一 ID 的过程的建议。
我的目的基本上是为每个请求提供一个唯一的 id 并将该 id 保存在数据库中,最后将该 id 与处理过的数据一起显示给用户,以便用户下次可以根据该 id 进行查询。
到目前为止我的理解是,我应该通过使用中间件来做到这一点。
我已经创建了一个处理数据的函数,比如:类中的处理数据。
我的路线是:
$app->group('/products', function() {
new \Products($this);
});
class Products
{
public function __construct($app)
{
$app->map(['GET','POST'], '/processed_data', [$this, 'processed_data']);
$c = $app->getContainer();
}
public function processed_data($request, $response, $next){
$data = array('name' => 'Bob', 'age' => 40);
/* I need to append $data in $response or in any container,
instead of writting here using write() method so that I
can use my $data in middleware for final processing or
simply say adding a unique id with this $data.*/
return $response;
}
}
我创建的中间件是:
class SendStandardResponse
{
public function __construct(){}
public function get_standard_request($request, $response, $next) {
// here I saved the request in the database
/*I want here to generate a unique id say : XXXXXX .
I am not sure where to append this unique id, either in
request or response or container. */
return $request;
}
/**
* recode_Response
*/
public function send_stardard_esponse($request, $response, $next) {
// here I saved the response in the database
/* get the output data from the processed_data function and add the unique id to response .
And finally send the response with $data and unique id by merging /
$data = array('name' => 'Bob', 'age' => 40, 'requestid' => 'xxxxxx');
and send it with response
*/
return $response;
}
public function __invoke($request, $response, $next)
{
$this->get_standard_request($request, $response, $next);
$response = $next($request, $response);
$this->send_stardard_esponse($request,$response, $next);
return $response;
}
}
【问题讨论】:
标签: slim