Type safe getters - PhpGt/Input GitHub Wiki

The Input class has type-safe getter functions assigned to it via the InputValueGetter trait:

  • getString(string $key):?string
  • getMultipleString(string $key):array<string>
  • getInt(string $key):?int
  • getMultipleInt(string $key):array<int>
  • getFloat(string $key):?float
  • getMultipleFloat(string $key):array<float>
  • getBool(string $key):?bool
  • getMultipleBool(string $key):array<bool>
  • getFile(string $key):?FileUpload
  • getMultipleFile(string $key):array<FileUpload>
  • getDateTime(string $key):?DateTimeInterface
  • getMultipleDateTime(string $key):array<DateTimeInterface>

The singular functions like getString, getInt, etc. all return nullable types. That is to say, they will attempt to return a typed value of the corresponding user input, but will return null if there is no user input supplied for the requested key.

The multiple functions like getMultipleString, getMultipleInt, etc. all return an array of the corresponding types. There may be zero elements in the array.

Accepting multiple fields of the same name

The getMultiple* functions will always return an array of values, corresponding to the values entered into elements with the same name attribute. It's important to know that PHP requires the use of square brackets within identical names. This is for two reasons: 1) to make PHP treat the incoming user input as an array; 2) to make it obvious and clear in the HTML that multiple inputs are expected.

Handling multiple checkboxes of the same name

Here's a common example of when multiple input elements may have the same name. When there's multiple elements to select using checkboxes, it makes sense for the checkboxes to share the same name. This example allows the user to make a choice of topping for their pizza.

HTML:

<form method="post">
	<p>Please select your pizza toppings:</p>

	<label>
		<input type="checkbox" name="topping[]" value="mozzarella" />
		<span>Mozzarella cheese</span>
	</label>
	<label>
		<input type="checkbox" name="topping[]" value="spinach" />
		<span>Spinach</span>
	</label>
	<label>
		<input type="checkbox" name="topping[]" value="tomato" />
		<span>Tomatoes</span>
	</label>

	<button name="do" value="submit">Submit</button>
</form>

PHP:

function do_submit(Pizza $pizza, Input $input):void {
// The value of $toppingsSelected is an array of strings, where
// the values are whatever values have been checked by the user.
	$toppingsSelected = $input->getMultipleString("topping");

	foreach($toppingsSelected as $topping) {
		$pizza->addTopping($topping);
	}
}

Next, learn how PHP handles files and how this library normalises the data.

⚠️ **GitHub.com Fallback** ⚠️