mechta-market/php-enhance

该包最新版本(1.2.0)没有可用的许可信息。

1.2.0 2024-07-16 12:35 UTC

This package is auto-updated.

Last update: 2024-09-20 05:08:27 UTC


README

BaseUsecase

usecase 的基本类,其子类聚集服务、启动过程、调用业务逻辑

BaseInput

用于从请求获取数据并将其传递给 usecase 的基本类

BaseOutput

用于从 usecase 操作收集数据的基类

Error

用于存储错误或异常信息的类

OutputError

用于存储 http 请求数据的类

Collection

用于处理数组的基类,示例在 ErrorCollection.php 和 OutputErrorCollection.php 中

日志记录

使用符合 Psr\Log\LoggerInterface 的任何日志记录器,通过构造函数加载到 usecase 中

控制器中使用 Usecase 的示例

public function index(Request $request, SomeUsecase $usecase)
{
    $input = new SomeInput($request->get('product_id'));

    $usecase->setInput($input);

    $usecase->execute();

    $response = $usecase->getOutput();

    if ($response->isFailed()) {
        abort($response->getStatusCode(), $response->getArrayResponse());
    }

    return $response->getArrayResponse();
}

usecase 工作示例

class SomeInput extends BaseInput
{
    public function __construct(private int $product_id){
    }

    public function getProductId(): int {
        return $this->product_id;
    }
}

class SomeUsecase extends BaseUsecase
{
    /**
     * @property SomeUsecaseData $data
     * @property SomeInput $input
     */
    public function execute(): void
    {
        try {
            $product_id = $this->input->getProductId();

            if ($product_id === 0) {
                throw new \Exception("Product id is zero");
            }

            $product = new Product(
                $product_id, "iPhone 15 Pro Max Ultra GigaByte",
                "iphone-15-super-puper", 999990
            );

            $this->data->setProduct($product);

        } catch (\Exception $ex) {
            $this->errors->addClientError($ex->getMessage(), 400);
        } catch (\Throwable $th) {
            $this->errors->addServerError($th->getMessage());
        }
    }

    protected function setData(): void
    {
        $this->data = new SomeUsecaseData();
    }
}

class SomeUsecaseData implements UsecaseDataInterface
{
    private Product $product;

    public function setProduct(Product $product): void {
        $this->product = $product;
    }

    public function getData(): array
    {
        return [
            "id" => $this->product->getId(),
            "name" => $this->product->getName(),
            "code" => $this->product->getCode(),
            "price" => $this->product->getPrice(),
        ];
    }
}