Your first payload
A hands-on tutorial: in about fifteen minutes you will build a tiny script that takes
a messy order payload — extra spaces, wrong casing, a price with a dollar sign — and
turns it into clean, typed values, without a single try/catch. You type, you run,
you see the output. That's the whole plan.
One thing to know before the first line. In a real handler the payload comes off the
request in one call, CkPayload::FromJson() — nothing passed means PHP's input, the request's
body — or, with the typed readers on it, CkRequest. A script has no
request to read, so the steps hand the same text to CkPayload::FromJson as a string instead;
everything after that call is identical, and step 9 puts the one line back.
You need the library in a project first — two minutes on Getting started if you haven't done it.
Step 1 — a project to play in
A folder with two files is enough — the script stands in for the handler you will write:
payload-tutorial/
├── composer.json
└── tutorial.php
composer.json brings the library in the way Getting started showed — here as a path
repository, pointing at the php/ folder of the repository cloned beside this one:
{
"repositories": [
{ "type": "path", "url": "../CommonKit/php" }
],
"require": {
"safecoder/commonkit": "@dev"
}
}
Run composer install. Then open tutorial.php, start it with <?php and
require __DIR__ . '/vendor/autoload.php';, and follow along — each step adds a few lines.
Run it after each step with:
php tutorial.php
Step 2 — the messy payload
Real payloads are never clean. Here is the one we'll tame — what arrives on the wire:
{
"customer": " mary-jane smith ",
"email": " Mary.Smith@GMAIL.com ",
"country": "usa",
"quantity": "3",
"price": "$19.99",
"giftNote": " "
}
Every field has a problem: stray spaces, double spaces, wrong casing, a country that isn't a code, a number that arrived as text, a price wearing a dollar sign, and a "note" that is only whitespace.
Step 3 — wire text into a bag
Paste the payload into the script as text, and let one call turn it into an array — CommonKit calls it the bag:
use SafeCoder\CommonKit\CkPayload;
$body = <<<'JSON'
{
"customer": " mary-jane smith ",
"email": " Mary.Smith@GMAIL.com ",
"country": "usa",
"quantity": "3",
"price": "$19.99",
"giftNote": " "
}
JSON;
$bag = CkPayload::FromJson($body);
echo 'fields: ' . count($bag) . PHP_EOL;
Run it:
php tutorial.php
fields: 6
If the text had not been valid JSON you would get an empty array — never a crash,
never a null. We'll prove that in step 7.
Step 4 — typed values out of the bag
CkDictionary reads values out by key. Ask for the type you want:
use SafeCoder\CommonKit\CkDictionary;
$bag = ['customer' => ' mary-jane smith ', 'quantity' => '3']; // the part of your bag this step reads
$rawName = CkDictionary::String(
dictionary: $bag,
key: 'customer'
);
$quantity = CkDictionary::Integer(
dictionary: $bag,
key: 'quantity'
);
echo 'name: [' . $rawName . ']' . PHP_EOL;
echo 'quantity: ' . $quantity . PHP_EOL;
name: [mary-jane smith]
quantity: 3
(The first line restates the part of the bag this step reads, so the block runs on its
own — the bag is a plain PHP array, which is all CkDictionary asks for. In tutorial.php
you have the whole bag from step 3; skip that line there, and in the steps that follow.)
Two things just happened quietly. The stray and doubled spaces are already gone —
String cleans as it reads. And "3" — a number that arrived as text, like form and
JSON values usually do — became a real int.
Step 5 — make each value the right kind of value
The domain classes each know one kind of data — names, emails, countries, money:
use SafeCoder\CommonKit\CkCountry;
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\CkText;
$bag = [ // the part of your bag this step reads
'email' => ' Mary.Smith@GMAIL.com ',
'country' => 'usa',
'price' => '$19.99',
];
$rawName = 'mary-jane smith'; // from step 4
$name = CkText::Name($rawName);
$email = CkEmail::Address(CkDictionary::String(dictionary: $bag, key: 'email'));
$country = CkCountry::Alpha2(CkDictionary::String(dictionary: $bag, key: 'country'));
$price = CkMoney::Amount(CkDictionary::Value(dictionary: $bag, key: 'price'));
echo $name . ' <' . $email . '> from ' . $country . ' pays ' . CkText::NumberToString($price) . ' each' . PHP_EOL;
Mary-Jane Smith <mary.smith@gmail.com> from US pays 19.99 each
Look at what you did not write: no trim(), no strtolower(), no
str_replace('$', '', …), no (float) cast. Each class did its own job. The one wrapper
you did write — CkText::NumberToString around the price — is there because a raw
$price in a string is written to your server's precision setting, fourteen digits by
default and whatever the host chose, so the same value can print differently on two
machines; step 8 turns that into a habit.
Notice the two ways a value came out of the bag. CkDictionary::String hands text to the
text classes — CkText, CkEmail, CkCountry read a string, and a number in the JSON
becomes its digits. CkDictionary::Value hands the value exactly as it sits in the bag to
the classes that judge a value of any type — CkMoney, CkNumber, CkDate — so a JSON
number stays a number.
Step 6 — the honest nothing
The gift note is three spaces — technically present, honestly nothing.
CkText::NullIfEmpty gives you the honest answer, ready for a nullable column:
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkText;
$bag = ['giftNote' => ' ']; // the part of your bag this step reads
$giftNote = CkText::NullIfEmpty(CkDictionary::String(dictionary: $bag, key: 'giftNote'));
echo 'gift note: ' . ($giftNote ?? '(none)') . PHP_EOL;
gift note: (none)
Step 7 — now break it
The best part. Point the same code at garbage and watch nothing crash:
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
use SafeCoder\CommonKit\CkText;
$broken = CkPayload::FromJson('{ this is not json'); // -> []
$brokenName = CkText::Name(CkDictionary::String(dictionary: $broken, key: 'customer'));
$brokenQuantity = CkDictionary::Integer(
dictionary: $broken,
key: 'quantity',
fallback: 1
);
echo 'broken fields: ' . count($broken) . PHP_EOL;
echo 'broken name: [' . $brokenName . ']' . PHP_EOL;
echo 'broken quantity: ' . $brokenQuantity . PHP_EOL;
broken fields: 0
broken name: []
broken quantity: 1
The bad JSON became an empty array. The missing name became ''. The missing quantity
became the fallback you chose. Every value tells you what happened — and your
script is still running.
Step 8 — write it out properly
One last habit — the one you glimpsed in step 5: values that leave your program are
written by the library, never by a raw echo of a float or by number_format — so the
output is identical on every machine, whatever its settings. For money there is a reader
that does the arithmetic too: CkMoney::Multiply works exactly — 19.99 × 3 in floating
point is not quite 59.97 — and answers numeric text with the currency's decimals, already
in the one invariant form, ready for a payload or a DECIMAL column:
use SafeCoder\CommonKit\CkMoney;
$quantity = 3; // from step 4
$price = 19.99; // from step 5
$total = CkMoney::Multiply(
input: $price,
factor: $quantity
);
echo 'total: ' . $total . PHP_EOL;
total: 59.97
A plain number that is not money — a count, a measurement — goes out through
CkText::NumberToString, as the unit price did in step 5.
Step 9 — the whole handler at a glance
That is the shape of every handler you will write with CommonKit. In a real signup
endpoint the same steps collapse into one constructor call — here with a birthday added,
the one kind of value the order did not have, and the request read by
CkRequest, which the script could not have: on first use it reads the
current request, as CkPayload::FromJson() with nothing passed would, and carries the CkDictionary readers
with it, so the bag and the key become one call and nothing is set up:
// no-check
use SafeCoder\CommonKit\CkCountry;
use SafeCoder\CommonKit\CkDate;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\CkRequest;
use SafeCoder\CommonKit\CkText;
$member = new Member(
name: CkText::Name(CkRequest::String('name')),
email: CkEmail::Address(CkRequest::String('email')),
country: CkCountry::Alpha2(CkRequest::String('country')),
birthday: CkDate::ToCarbonDayOrNull(CkRequest::String('birthday')),
budget: CkMoney::Amount(CkRequest::String('monthlyBudget'))
);
CkRequest reads the request PHP is serving the first time it is asked — the raw query string
on GET, a JSON or form body on any other method, PUT and PATCH included, picked by the method
and the content type — where the tutorial handed FromJson a string; CkRequest::String('name')
is CkDictionary::String on the bag it holds. Where the handler itself lives
— a route, a controller, an action hook — is the framework's business, and each framework
page shows the place: Using it with Laravel, Using it with Joomla!
and Using it with WordPress. Five lines of intake into a Member whose
constructor takes those five, and every value is clean, typed and safe — with not a single
try/catch in sight. Two things to notice:
birthdayis a?CkDayread with the…OrNulltwin — a calendar day with no time of day, never moved by a time zone — so a nullable column gets an honestNULLwhen the field is missing, unreadable or a placeholder like1900-01-01. A date such as"07/21/1990"reads month-first by default; pass aDateOrderwhen your users write day-first.- The strings are the plain readers: a bad email is
'', andCkText::NullIfEmptybridges it tonullwhere the column is nullable — or, saving through a framework's model, one hook does that for every attribute at once withCkSentinel::ToNull, shown on the same framework pages.
If you want to reject the request when a required value fails, check the rejection values
('', null, your fallback) — or pass throwIfInvalid: true where a failure should stop
the show. To answer the client with every problem at once, in the readers' own words, put
a validator in front of this handler.
What you just learned
- The pipeline: CkPayload gets text off the wire, CkDictionary gets typed values out of the bag, the domain classes make each one the right kind of value, and CkSentinel nulls the placeholders on the way to storage.
- Nothing throws. Bad input answers
'', yourfallback, ornull— you saw all three. - Data leaving the program is written by the library —
CkMoney::Multiply's text,CkText::NumberToStringand friends.
Where next
- How it works — the five rules, and which reader to call.
- Common mistakes — the traps everyone hits once with the library itself.
- Writing a validator — every problem with a payload, reported at once.
- Setting up your file places — the platform's folders for every kind of file, or one root of your own, and the rules each place keeps.
- Using it with a framework — Laravel, Joomla! and WordPress: the way in, reading the request, validating, one
ToNullon the way to the database, and where the files go.