PHP code example of maartenpaauw / laravel-specification-pattern

1. Go to this page and download the library: Download maartenpaauw/laravel-specification-pattern library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maartenpaauw / laravel-specification-pattern example snippets


return [
    'collection-method' => 'matching',
];



namespace App\Specifications;

use Maartenpaauw\Specifications\Specification;

/**
 * @implements  Specification<mixed>
 */
class AdultSpecification implements Specification
{
    /**
     * {@inheritDoc}
     */
    public function isSatisfiedBy(mixed $candidate): bool
    {
        return true;
    }
}

class Person {
    public function __construct(public int $age)
    {}
}

$specification = new AdultSpecification();

// ...

$specification->isSatisfiedBy(new Person(16)); // false
$specification->isSatisfiedBy(new Person(32)); // true

$persons = collect([
    new Person(10),
    new Person(17),
    new Person(18),
    new Person(32),
]);

// ...

// Returns a collection with persons matching the specification
$persons = $persons->matching(new AdultSpecification());

// ...

$persons->count(); // 2
shell
php artisan make:specification AdultSpecification