Skip to content

Core\Request::method

Returns the method of the request, such as GET or POST, as a case of the enum Core\Http\Method. You compare it with a case: Core\Request::method() == Core\Http\Method::Post.

The method says what the client wants to do. GET reads a page, POST sends a form, PUT and PATCH change something, and DELETE removes it. One address often does different things for different methods.

A HEAD request returns Get, because Novis runs it the same way as a GET request. Use Core\Request::isHead when you need to tell the two apart.

A command-line program answers no request, so method throws a LogicError there. The examples below show a form that is shown or saved, a page that answers 405 for a method it does not support, and one address that reads, changes and deletes a record.

Return value

Returns Core\Http\Method. The Core\Http\Method case of the request. It is never Head.

Errors

  • LogicErrorThe program is not handling a request, such as a command-line program or a test. It is also thrown when the method is not one of the cases of Core\Http\Method. The server answers such a request with 501 before your program runs.

Examples

Showing or saving a form

<?nvs
// Shows how one page shows a form for `GET` and saves it for `POST`.
// The request below uses the method `POST`, so this prints "Saving the form.".
if (Core\Request::method() == Core\Http\Method::Post) {
echo "Saving the form.\n";
} else {
echo "Showing the form.\n";
}
Output
Saving the form.

Refusing a method the page does not support

<?nvs
// Shows how a page that supports only `GET` and `POST` answers any other method.
var $method = Core\Request::method();
// The request below uses `DELETE`. This page does not support it.
// The status `405` means "method not allowed". This prints "405, allowed: GET, POST".
if ($method == Core\Http\Method::Get || $method == Core\Http\Method::Post) {
echo "200\n";
} else {
echo "405, allowed: GET, POST\n";
}
Output
405, allowed: GET, POST

One address for a record

<?nvs
// Shows how one address of an API reads, changes or deletes a record, depending on the method.
// `match` checks the method and gives one text for each case.
// `default` is used for every method that is not listed.
var $action = match (Core\Request::method()) {
Core\Http\Method::Get => 'read order 1042',
Core\Http\Method::Put, Core\Http\Method::Patch => 'change order 1042',
Core\Http\Method::Delete => 'delete order 1042',
default => 'method not allowed',
};
// The request below uses `PATCH`. This prints "change order 1042".
echo $action, "\n";
Output
change order 1042