Constructing the Input class - phpgt/Input GitHub Wiki
Input is the main entry point to the library. It represents:
- query string data
- request body fields
- uploaded files
- the raw request body stream
In plain PHP, we usually construct it from the PHP superglobals:
use GT\Input\Input;
$input = new Input(
$_GET,
$_POST,
$_FILES,
"php://input",
$_SERVER["REQUEST_METHOD"] ?? "GET"
);
The fourth argument is the path to the request body stream, which defaults to "php://input". The fifth argument is the HTTP method, which matters when we want to work with PUT upload streams.
Working with a specific part of the request
The same Input object can read from different sections of the request. For example:
$page = $input->get("page", Input::DATA_QUERYSTRING);
$search = $input->get("q", Input::DATA_BODY);
$avatar = $input->getFile("avatar");
If no method is provided, Input reads from the combined request data.
The available method constants are:
Input::DATA_QUERYSTRINGInput::DATA_BODYInput::DATA_FILESInput::DATA_COMBINED
Working with all request data
Sometimes we need the whole input collection rather than a single value:
$all = $input->getAll();
$queryOnly = $input->getAll(Input::DATA_QUERYSTRING);
$bodyOnly = $input->getAll(Input::DATA_BODY);
$filesOnly = $input->getAll(Input::DATA_FILES);
These calls return InputData objects, which are iterable, countable, array-accessible, and can also use the same type-safe getters as Input.
Usage within WebEngine
In WebEngine applications we do not usually construct Input ourselves. The framework puts it in the service container and injects it into go() and do_*() functions for us:
use GT\Input\Input;
function do_save(Input $input, ProfileStore $profiles):void {
$profiles->saveName($input->getString("name"));
}
That means the same API works whether we are writing a standalone PHP script or a WebEngine application.
Next: Type-safe getters