Skip to content

Validator interface ​

composer require quillstack/validator-interface

Common interface for Validator classes.

One method, and two exception interfaces. Something which validates says so by implementing this, and something which fails validation says so by implementing the other — so a caller can tell a value it does not like from a mistake in the code.

Why this exists ​

Validation is the one part of an application that everybody writes differently, and the one part that everything else needs to be able to ask about. A request wants to know whether what arrived is acceptable; it should not need to know how that was decided.

This is that question as an interface, in its own package, so a package can depend on something validating without depending on how.

Requirements ​

  • PHP 8.1 or newer

Installation ​

shell
composer require quillstack/validator-interface

Usage ​

php
use Quillstack\ValidatorInterface\ValidatorInterface;

final class HostValidator implements ValidatorInterface
{
    public function __construct(private readonly string $host)
    {
    }

    public function validate(): bool
    {
        if (filter_var($this->host, FILTER_VALIDATE_DOMAIN) === false) {
            throw new UnknownHostException("Not a host: {$this->host}");
        }

        return true;
    }
}

The exception says which kind of thing went wrong:

php
use Quillstack\ValidatorInterface\ValidationExceptionInterface;

final class UnknownHostException extends UriException implements ValidationExceptionInterface
{
}

Catching it is then catching one thing:

php
try {
    $validator->validate();
} catch (ValidationExceptionInterface $exception) {
    // What was given is wrong — not the code that was given it.
}

Technical documentation ​

InterfaceWhat it means
ValidatorInterfacevalidate(): bool — the thing validates something
ValidatorExceptionInterfacesomething went wrong in a validator
ValidationExceptionInterfacethe value was wrong, which is the usual case; extends the one above

validate() answers true or throws. It does not answer false: a caller which ignores the answer would carry on with a value nobody accepted, and a thrown exception cannot be ignored by accident.

Who implements it ​

There is nothing to run here: a package which only names things has no behaviour to test.

Benchmark ​

There is nothing here to measure.

This package is an interface. It has no behaviour of its own, so there is no operation to time and no library that does the same nothing to compare it with.

What is worth comparing is an implementation, and the honest place for that table is in whichever package implements it rather than here.

Tests ​

shell
composer test
composer stan

The rest of Quillstack ​

This is one component of Quillstack, a PHP framework which is as simple to use as it is strict about what it does.

License ​

MIT. See LICENSE.

Released under the MIT License.