Hi.
I am updating Slim v2.6.4 to v4.3.0.
All is working, except that I having trouble to create a function to create response.
With v2.6.4 I was using the following approach:
$app->post(’/hello’, function () use ($app) {
$nome = $app->request->post('nome');
$sobrenome = $app->request->post('sobrenome');
$resposta = array();
$resposta["nome"] = $nome;
$resposta["sobrenome"] = $sobrenome;
RespostaAplicativo(200, $resposta);
});
function RespostaAplicativo($status_code, $response)
{
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType(‘application/json’);
echo json_encode($response);
}
This is what I am trying with v4.3.0
$app->post(’/hello’, function (Request $request, Response $response, $args) {
$body = $request->getParsedBody();
$nome = $body[‘nome’];
$sobrenome = $body[‘sobrenome’];
$resposta_aplicativo = array();
$resposta_aplicativo[“nome”] = $nome;
$resposta_aplicativo[“sobrenome”] = $sobrenome;
/*
**WORKING CODE, BUT, NEED TO WORK AS FUNCTION**
$payload = json_encode($resposta_aplicativo);
$response->getBody()->write($payload);
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(200);
*/
RespostaAplicativo(201, $resposta_aplicativo, $response);
});
function RespostaAplicativo($status_code, $dados, Response $response)
{
$payload = json_encode($dados);
$response->getBody()->write($payload);
return $response
->withHeader(‘Content-Type’, ‘application/json’)
->withStatus($status_code);
}
Type: TypeError
Code: 0
Message: Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, null returned
File: vendor\slim\slim\Slim\Handlers\Strategies\RequestResponse.php
Line: 42