Assertion Library for PHP

Assertion Library for PHP

Assert is a composer package by Benjamin Eberlei which serves as a “thin assertion library for input validation in business models.”

Idea is to reduce the amount of code for implementing assertions in your model and also simplify the code paths to implement assertions. When assertions fail, an exception is thrown, removing the necessity for if-clauses in your code.

Here’s a basic example usage from the README:

use Assert\Assertion;

function duplicateFile($file, $times)

    for ($i = 0; $i < $times; $i++) {
        copy($file, $file . $i);

This package has many assertions, including an “all” helper which checks all provided values against a given assertion:

Assertion::isInstanceOf($value, $className);

Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'stdClass'); // success
Assertion::allIsInstanceOf(array(new \stdClass, new \stdClass), 'PDO');      // exception

One thing to note: assertions throw an exception if the assertion fails, thus potentially avoiding conditionals in your code around assertions.

If you need low-level code assertions, this library is packed full of useful assertion methods and strategies like lazy assertions where you may want to collect multiple errors at once instead of failing on the first assertion:

    ->that(10, 'foo')->string()
    ->that(null, 'bar')->notEmpty()
    ->that('string', 'baz')->isArray()

Check out the readme for a full list of available assertions and to learn more about how to use this library in your projects. You can get full installation instructions and view the source code on GitHub at beberlei/assert.

Filed in: News
Laravel News Partners

Laravel Jobs

PHP Developer - Full time w/ benefits, US Only
Northern Virginia or Remote (US Only)
Guidance Residential
Full Stack Developer
Laravel API Developer
Las Vegas, NV (Must work on-site)
V Shred
Laravel Developer (Vue, SQL Server)
World Trade Organization
Web Application Developer (Vue.js & Laravel)
Apero Creative Development


Join 31,000+ others and never miss out on new tips, tutorials, and more.