Slim v4 - Function for Response

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

At a glance it seems like the problem is that you don’t return the response returned by RespostaAplicativo(), hence your inline function for /hello returns null instead of the response.

OMG.

So stupid :sweat_smile: :joy:

You are right. Thank u soo much cess11.

This work as expected.

from
RespostaAplicativo(201, $resposta_aplicativo, $response);
to
return RespostaAplicativo(201, $resposta_aplicativo, $response);

1 Like