zheltikov/php-pipeline

1.0.0 2021-07-15 18:49 UTC

This package is auto-updated.

Last update: 2024-09-16 02:05:26 UTC


README

这是一个提供处理管道操作实用函数的库。

安装

要安装此库,请使用Composer

$ composer require zheltikov/php-pipeline

使用方法

以下是一个简单示例,说明了如何在基本级别上使用此库

<?php

require_once(__DIR__ . '/../vendor/autoload.php');

use function Zheltikov\Pipeline\pipeline;

$work = pipeline(function ($resolve, $reject) {
        // do some interesting work...
        // for illustration purposes, just randomize the result
        rand(0, 1)
            ? $resolve(123) // pass the result value of the work
            : $reject(new \Exception('Some error'));
    })
    // on each step of the pipeline, do something with the result of the
    // previous step and pass it forward
    ->then(fn($x) => $x ** 2) 
    ->then(fn($x) => $x + 1)
    ->then(fn($x) => $x / 123)
    ->then(fn($x) => sqrt($x))
    ->catch(function ($reason) {
        // do something when an error occurs in the pipeline
        // for example, you can log it, for later analysis
        \Logger::log($reason);
    })
    ->finally(function () {
        // do something regardless if the work succeeded of failed
        // for example you can close some file or connection
        fclose($some_file);
        mysqli_close($connection);
    });

// You are given some methods to gather information about the pipeline
if ($work->isResolved()) {
    // The pipeline succeeded
    $result = $work->getValue();
}

if ($work->isRejected()) {
    // The pipeline failed
    $reason = $work->getReason();
}

// We can even add pipeline steps afterwards...!
$work->then(fn($x) => $x * $x)
    // ...
    ->catch('var_dump')
    ->finally(function () { /* ... */ });

正如您所看到的,此库提供的接口类似于JavaScript中的Promise对象,但遗憾的是,它不提供异步支持... 猜猜为什么! :)

您可以在源代码中寻找更多使用此库的方法。