Skip to content

Parameter bag

composer require quillstack/parameter-bag

Simple key-value storage.

The bag the rest of the stack keeps things in: query parameters, cookies, server variables, a parsed body. A missing key answers with the default rather than a warning, which is what reading from a request needs.

Requirements

  • PHP 8.1 or newer

Installation

shell
composer require quillstack/parameter-bag

Usage

php
use Quillstack\ParameterBag\ParameterBag;

$bag = new ParameterBag(['page' => '2', 'sort' => 'email']);

$bag->get('page');            // '2'
$bag->get('perPage', '20');   // '20' — nothing under that name, so the default
$bag->has('sort');            // true
$bag->all();                  // ['page' => '2', 'sort' => 'email']

$bag->set('page', '3');
$bag->remove('sort');         // true, and false where there was nothing to remove

set() hands the bag back, so several can be written in one go:

php
$bag->set('host', 'localhost')->set('port', 5432);

Where it is used

quillstack/server-request keeps every part of a request in one: $_SERVER, $_COOKIE, $_GET, $_FILES and the parsed body are each a bag, so reading a key that was not sent is an answer rather than a notice.

Technical documentation

MethodDoes
__construct(array $parameters = [])starts with what it is given
get(string $name, mixed $default = null): mixedthe value, or the default
set(string $name, mixed $value): selfwrites one, and hands the bag back
has(string $name): boolwhether there is one under that name
remove(string $name): booltakes one out; false where there was none
all(): arrayeverything in it

This is a mutable bag on purpose: a request is built up before it is handled, and copying it for every parameter would cost more than it is worth. The PSR-7 objects around it are the ones which are immutable.

Unit tests

shell
composer test
composer test:coverage
composer stan

Docker

shell
docker-compose up -d
docker exec -w /var/www/html -it quillstack_parameter-bag sh

License

MIT. See LICENSE.

Released under the MIT License.