SLIM 4 - Using the same callback function for different routes

22 views Asked by At

Good evening everybody.

I have a small API with a couple of similar looking endpoints. So I'd like to use the same callback function for both of them. For this purpose, I need to send a variable to the callback function to make this function act in a different way.

I tried something like that:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

$app = AppFactory::create();
$app->post('/dosomething', function(Request $req, Response $res){
  callback($req, $res, "valueA");
}

$app->post('/dosomethingelse', function(Request $req, Response $res){
  callback($req, $res, "valueB");
}
    
function callback(Request $request, Response $response, $myparameter ){

  // ... do some common stuff before using $myparameter...

  if($myparameter=='valueA') {
    $response->getBody()->write('I did something');
    return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
  }

  if($myparameter=='valueB') {
    $response->getBody()->write('I did something else');
    return $response->withStatus(200)->withHeader('Content-Type', 'application/json');
  }
}

I receive this error:

Fatal error: Uncaught TypeError: Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must implement interface Psr\Http\Message\ResponseInterface, null returned in /var/www/html/myproject/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php:38

What's the matter? $myparameter is received correctly ( I tested it ), so I believe there's something wrong with the other two variables.

Need some help, thanks!

0

There are 0 answers