When I should kill a route from continuing, what is the correct way to break it?
Example:
Instead of an else statment, in this case I use die; to just kill it off:
kirby()->routes(array(
array(
'pattern' => 'test',
'action' => function() {
if(1==1) {
echo 'Do something';
die;
}
echo 'Do something else';
}
));
In this particular example I would probably use else in real life
As far as I know there are these ways to break a route:
die;
exit;
return false;
return null;
return;
Which do you prefer and why? I think I prefer die; because then I know nothing will run after that.
Normally an HTTP request is initiated by a client that expects a response back. For that reason I prefer to return an HTTP response with proper status code even in cases I don’t really need one:
return new Response("You can't access this page.", 'html', 403);
For JSON responses Kirby offers some aliases:
return response::success($message, $data = [], $code = 200);
// or
return response::error($message, $code = 400, $data = []);
When you return a response nothing after it gets executed.
For this case I think the first example is brilliant!
In fact it does 3 things in one row. It give an error message, setting the content type and setting a status code. It also seems to be an undocumented feature?
Looking at the docs https://getkirby.com/docs/developer-guide/advanced/routing, it says to stop the app, use return false;.
Maybe make the response class official and add this instead of return false; to the routes page in the docs?
Update
I’ve also updated https://github.com/jenstornell/kirby-secrets/wiki/Advanced-routes with this new information.
If there is a need to style the message, it’s also possible to use a snippet:
return new Response(snippet('error-message', [], true), 'html', 404);
The response class is actually used in another example in those docs:
Returning a response object
function() {
return response::json(array(
'some', 'json', 'stuff'
));
}
But yes, the docs could certainly be extended with some more examples.
Yes, I saw that.
The @pedroborges alternative syntax (alternative facts ;)) is not a singleton call and it’s setting an error message so there is a difference. So yes, I think yet another example would not hurt.
But you (and the other crew) are really good at docs in general. It’s really hard to find “doc holes”. 
It’s documented only on the Toolkit section: https://getkirby.com/docs/toolkit/api#response
The best resource for me to learn how to use classes like this has been reading Kirby’s core and panel code. Lot’s of hidden gems in there 
Yes, that often helps a lot.