kaivladimirv/laravel-specification-pattern

v1.0.0 2023-08-30 03:44 UTC

This package is auto-updated.

Last update: 2024-09-30 06:02:38 UTC


README

code style type coverage psalm level tests sast Maintainability Test Coverage Latest Version License PHP Programming Language

Laravel的规范模式

在PHP中实现规范模式

要求

  • PHP 8.1+

安装

您可以通过composer安装此包

$ composer require kaivladimirv/laravel-specification-pattern

使用方法

您可以使用artisan命令创建一个规范

$ php artisan make:specification GreaterThanSpecification

此命令将在App\Specifications命名空间中创建一个规范类

<?php

declare(strict_types=1);

namespace App\Specifications;

use Kaivladimirv\LaravelSpecificationPattern\AbstractSpecification

class GreaterThanSpecification extends AbstractSpecification
{
    protected function defineMessage(): string
    {
        // TODO: Implement defineMessage() method.    
    }

    protected function executeCheckIsSatisfiedBy(mixed $candidate): bool
    {
        return false;
    }
}

向创建的规范添加业务逻辑

<?php

declare(strict_types=1);

namespace App\Specifications;

use Kaivladimirv\LaravelSpecificationPattern\AbstractSpecification

class GreaterThanSpecification extends AbstractSpecification
{
+    public function __construct(readonly private int|float $number)
+    {
+    }
+    
    protected function defineMessage(): string
    {
-        // TODO: Implement defineMessage() method.
+        return "Number must be greater than $this->number";    
    }

    protected function executeCheckIsSatisfiedBy(mixed $candidate): bool
    {
-        return false;
+        return $candidate > $this->number;
    }
}

添加业务逻辑后,您可以通过调用isSatisfiedBy或throwExceptionIfIsNotSatisfiedBy方法来使用规范

使用isSatisfiedBy方法

$greaterThan100Spec = new GreaterThanSpecification(100);

$greaterThan100Spec->isSatisfiedBy(200); // true
$greaterThan100Spec->isSatisfiedBy(99); // false

使用throwExceptionIfIsNotSatisfiedBy方法

$greaterThan100Spec = new GreaterThanSpecification(100);

$greaterThan100Spec->throwExceptionIfIsNotSatisfiedBy(200); // No exception will be thrown here
$greaterThan100Spec->isSatisfiedBy(99); // An DomainException will be thrown here with the message "Number must be greater than 100"

您可以在getExceptionClass方法中更改异常类型

<?php

declare(strict_types=1);

namespace App\Specifications;

use Kaivladimirv\LaravelSpecificationPattern\AbstractSpecification

class GreaterThanSpecification extends AbstractSpecification
{
    public function __construct(readonly private int|float $number)
    {
    }
    
    protected function defineMessage(): string
    {
        return "Number must be greater than $this->number";    
    }

    protected function executeCheckIsSatisfiedBy(mixed $candidate): bool
    {
        return $candidate > $this->number;
    }
+    
+    protected function getExceptionClass(): string
+    {
+        return MyException::class;
+    }
}

许可证

Task manager项目使用MIT许可证(MIT)授权。有关更多信息,请参阅LICENSE