【发布时间】:2018-10-11 14:53:55
【问题描述】:
我创建了一个简单的 rest api 来处理一些 POST 数据。我想在发送响应之前添加一些功能来清理数据。
我是 Slim 和 PHP 的新手,所以不确定这是否可行/我正在使用“正确”的方法解决问题。
这是我目前的尝试(不起作用!)调用了中间件,但进程函数总是返回 NULL
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require __DIR__ . '/../vendor/autoload.php';
$app = new \Slim\App();
// add function to $app
$app->process = function ($request, $response, $next) use($app) {
return 'process';
};
$process = $app->process;
// middleware
$mw = function ($request, $response, $next) {
$response = $next($request, $response);
// should return string from above function
$variable = $process
$data = array('name' => $name, 'process' => $variable);
$newResp = $response->withJson($data);
return $newResp;
};
$app->post('/api/name', function (Request $request, Response $response, array $args) {
$parsed= $request->getParsedBody();
$response = $response->withStatus(200);
})->add($mw);
$app->run();
【问题讨论】: