Why Assert
Most PHP validation tools fall into one of two kinds:
- Assertion helpers such as
Assert::integer($x)check one value at the call site and throw on the first failure. They are quick to write, but you cannot store such a check, reuse it, or get all the failures at once. - Validator frameworks describe the shape of an object with constraints or attributes. They are powerful, but comparing one field with another usually needs a callback or an expression language, and the result is tied to the framework.
Assert sits in between. A rule is a plain immutable object. You build it from small parts, keep it in a constant or a service, and apply it to any data:
php
use EugeneErg\Assert\Assert;
$range = Assert::lessThanOrEqual(Assert::ref('from'), Assert::ref('to'));
$range->validate(['from' => 1, 'to' => 5]); // true
$range->assert($request); // throws ValidationException with every violationWhat it gives you:
- References between fields.
Assert::ref('to'),Assert::parent(2, 'maxQty'),Assert::length(...)andAssert::count(...)work anywhere a value does. - Negation you can trust.
not()turns any rule into its opposite, composites included. The message says what had to be true: "value must not be empty". - Strict comparisons.
"10"is never compared with9as a string. A mix of kinds is reported, not silently mis-sorted. - Structured results. Every violation has a code, a path, parameters and a readable message, so the same rule serves an exception, an API response and a translated UI.
When not to use it
- Mapping input to objects. Assert checks data; it does not hydrate DTOs. Use it before or after your mapper.
- Framework forms. If your framework already validates forms with its own constraints and error rendering, keep using them there.
See the comparison with Respect\Validation, Laravel validation and webmozart/assert, with benchmarks.