inmanturbo/functional-library

轻松创建用于PHP函数式编程的闭包库

v1.0.0 2024-08-12 20:03 UTC

This package is auto-updated.

Last update: 2024-09-19 22:11:55 UTC


README

Latest Version on Packagist Tests Total Downloads

此包使得使用composer轻松导出和自动加载匿名函数库或匿名函数集合变得容易。

安装

您可以通过composer安装此包

composer require inmanturbo/functional-library

使用方法

要创建库,您可以使用HasFunctionalLibrary特质,然后只需实现一个具有命名布尔参数的静态库方法,以供您可用的函数使用。

然后,您使用所有参数作为其args调用static::getLibrary

最后,您创建一个名为closures()的静态方法,该方法包含一个关联数组,其中包含您的匿名函数,键对应于库方法的命名参数。

示例

use Inmanturbo\FunctionalLibrary\HasFunctionalLibrary;

class ExampleLibrary
{
    use HasFunctionalLibrary;

    public static function library(bool $addOne = false, bool $addTwo = false)
    {
        return static::getLibrary(...func_get_args());
    }

    public static function closures()
    {
        return [
            'addOne' => fn(int $number): int => $number + 1,
            'addTwo' => fn(int $number): int => $number + 2,
        ];
    }
}

示例用法

上面的示例创建了以下可测试的API(使用pest)

[$addOne, $addTwo] = ExampleLibrary::library(addOne: true, addTwo: true);
expect($addOne(0))->toBe(1);
expect($addTwo(0))->toBe(2);

// Test a single option
$addOne = ExampleLibrary::library(addOne: true);

expect($addOne(0))->toBe(1);

// Test no options (should return all available options)
[$addOne, $addTwo] = ExampleLibrary::library();

expect($addOne(0))->toBe(1);
expect($addTwo(0))->toBe(2);

现在,您可以将匿名函数放入作用域内的静态库中,并通过它们的命名参数或通过检查closures()方法的返回值来查找它们。

测试

composer test

变更日志

有关最近更改的更多信息,请参阅变更日志

贡献

有关详细信息,请参阅贡献指南

安全漏洞

请审查我们的安全策略,了解如何报告安全漏洞。

致谢

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件