SLIM framework Halt call
-
01-06-2021 - |
Domanda
Have a question on Slim Framework php.
In my application, I would like to stop the application execution if a condition is mismatched.
There is a halt function, per Slim documentation. But that does not appear to be working. the application continuous to execute even after calling Halt.
pseudo code:
if ( $valid ) {
// Do something
} else {
$app->halt(500, "not valid");
}
// Other code here.
$app->run();
I was expecting that, we we call Halt function, the "Other code" should not execute. But it does not appear to be the case.
Any ideas?
Soluzione
You can always call exit
manually to stop the script execution.
$app->halt(500, "not valid");
exit;
Altri suggerimenti
Halt should work. As Josh mentioned, it does need to be called from within a route callback. For example, I use the following as a custom 404 (inside of index.php) in the event that a specified route is not found.
// not found (custom 404)
$app->notFound(function () use ($app) {
// build response
$response = array(
'type' => 'not_found',
'message' => 'The requested resource does not exist.'
);
// output response
$app->halt(404, json_encode($response));
});
Note the reference to use ($app) -- more on this can be found here: http://www.slimframework.com/documentation/stable#scope-resolution
Halt should only be invoked within the context of a route callback. I recommend you ask any further questions on the official Slim Framework support forum:
Best regards, Josh
You can use return if you are in a callback function
return $app->halt(500,"message");
or
$app->stop();
after halt function.