axm/fluent

PHP 的 Fluent 接口

1.0.8 2024-01-24 23:53 UTC

This package is auto-updated.

Last update: 2024-09-25 01:08:53 UTC


README




Latest Stable Version Total Downloads License



Fluent 接口

FluentInterface 类是一个 PHP 工具,它为链式方法调用和简明控制 PHP 操作流程提供流畅的接口。其主要目的是提高代码可读性,让您能够连贯地链式调用一系列方法,易于理解。这是此接口的最大潜力,不再需要重复返回 $this 对象,现在 FluentInterface 会自动为您处理。

📦 安装

您也可以使用 Composer 快速在项目中安装 Axm。

composer require axm/fluent

方法链式调用

您可以链式调用多个方法,这有助于顺序执行多个操作。例如

$result = __(new MyClass)
    ->method1()
    ->method2()
    ->method3()
    ->get();

流程控制

该类允许使用 if、elseif 和 else 条件精确控制方法执行流程。这对于根据特定条件运行特定操作很有用。例如

$result = __(User::class)
    ->if(fn ($user) => $user->isAdmin())
    ->setProperty('type', 'admin')
    ->return('You are an admin.')

    ->elseif(fn ($user) => $user->isUser())
    ->setProperty('type', 'user')
    ->return('You are a user.')

    ->else()
    ->setProperty('type', 'unknown')
    ->return('You are not logged in.')
    ->get();

动态实例创建

您可以动态创建类实例并将它们设置为当前对象。这在需要灵活地处理不同对象时很有用。例如

$result = __(new MyClass)  //new instance
    ->method1()
    ->method2()
    ->new('SomeClass')    //resets the previous intent with a new `FluentInterface` class to continue chaining.
    ->method1()
    ->method2()
    ->method3()
    ->new('OtherClass')    //resets the previous intent with a new `FluentInterface` class to continue chaining.
    ->method1()
    ->method2()
    ->method3()

    ->get('method1');   //gets the value in this case of the return of method 1 of the last instance

异常处理

FluentInterface 类处理异常,并允许在执行过程中抛出异常,使基于条件的决策和抛出的异常更加容易。

$result = __(new MyClass)
    ->boot()
    ->getErrors()
    ->throwIf(fn ($user) => $fi->get('getError') > 0, , 'An error has occurred while initializing.')

调试函数

它提供了 dd()、dump() 和 echo() 等方法来帮助调试和分析结果。

dd() 方法

dd() 方法(dump and die)用于调试和分析 FluentInterface 类的结果。您可以使用它来详细显示当前变量的内容。如果您提供了一个键 ($key),则只显示结果中的特定条目。用法示例

$result = __(new MyClass)
    ->increment(10)
    ->duplicate()
    ->dd();
dump() 方法

dump() 方法用于调试和分析 FluentInterface 类的结果。与 dd() 类似,您可以提供一个键 ($key) 以显示结果中的特定条目。用法示例

$result = __(new MyClass)
    ->increment(10)
    ->duplicate()
    ->dump('duplicate');       //will return the value of the duplicate method call.
echo() 方法

echo() 方法用于打印 FluentInterface 类的结果。您可以可选地提供一个值 ($value) 以打印特定内容。如果没有提供值,它将打印所有当前结果。用法示例

$result = __(new MyClass)
    ->increment(10)
    ->duplicate()
    ->echo();

使用自定义方法

除了内置方法外,您还可以使用 addCustomMethod() 添加自己的自定义方法。这根据您的特定需求扩展了类的功能。

$result = __(new MyClass)
    ->addCustomMethod('call', function ($obj) {
    // Define your own logic here
    })
    ->addCustomMethod('getName', function ($obj) {
    // Define your own logic here
    })
    ->call()
    ->getName()
    ->all();

与 Laravel 集合接口

该类可以与 Laravel 集合一起工作,并在它们上运行集合方法。您只需将数组作为参数传递给 FluentInterface 类即可。例如

$collection = [
    ['name' => 'John Doe',  'age' => 30],
    ['name' => 'Jane Doe',  'age' => 25],
    ['name' => 'John Smith','age' => 40],
];

$result = __($collection)
    ->filter(function ($item) {
        return $item['age'] > 25;
    })
    ->sort(function ($a, $b) {
        return $a['name'] <=> $b['name'];
    });

$result->all();
使用对象演示 Fluent 接口的使用示例。

示例 1:对数值的操作 本例说明了 MyClass 类的使用,该类提供了对数值执行操作流畅的接口。MyClass 类有三个主要方法:increment()duplicate()getValue()

class MiClase
{
    public $value = 0;

    public function increment($cantidad)
    {
        return $this->value += $cantidad;
    }

    public function duplicate()
    {
        return $this->value *= 2;
    }

    public function getValue()
    {
        return $this->value;
    }
}

Fluent 接口实现

$res = __(MiClase::class)
    ->increment(5)
    ->duplicate()
    ->increment(5)

    ->if(fn ($fi) => $fi->value > 20)
    ->increment(5)

    ->elseif(fn ($fi) => $fi->value < 15)
    ->increment(10)

    ->else()
    ->increment(10)

    ->getValue()->dd('getValue');

示例 2:用户输入验证 本例展示了如何验证用户输入并根据特定条件做出决策。FluentInterface 类提供了一个流畅的接口,以有效地链式调用方法和控制执行流程。

__($request->input())   //input array

    ->if(fn ($item) => $item['name'] === '')
    ->throwIf(true, 'The name field is required.')

    ->if(fn ($item) => $item['email'] === '')
    ->throwIf(true, 'The email field is required.');

    ->new(Auth::class)     // Create a new instance of the class 'Auth'.
    ->if(fn ($user) => $user->hasPermission('admin'))
    ->return(['Admin Dashboard', 'User Management','Role Management',])

    ->elseif(fn ($user) => $user->hasPermission('user'))
    ->return(['My Profile','My Orders','My Account',])

    ->else()
    ->return(['Login','Register',])
    ->get('return');

示例 3:动态报告生成 假设您正在开发一个报告生成流畅化,允许用户根据其需求配置和自定义报告。在这种情况下,FluentInterface 可以简化动态报告的构建。

假设您有一个用于构建报告的ReportBuilder类。您可以使用FluentInterface链式调用方法,并动态配置报告组件,如标题、图表、数据和输出格式。

// Create a custom report using FluentInterface.
__(ReportBuilder::class)
    ->setHeader('Informe de Ventas')
    ->setSubtitle('Resultados mensuales')
    ->setChart('Ventas por mes', 'bar')
    ->addData('Enero', 1000)
    ->addData('Febrero', 1200)
    ->addData('Marzo', 800)
    ->setFooter('© 2023 Mi Empresa')
    ->setFormat('PDF')
    ->generateReport();

示例4:构建可配置表单想象您正在开发一个表单构建平台,用户可以设计自己的表单并添加自定义字段。FluentInterface可以简化动态表单的创建和操作。

 __(FormBuilder::class)
    ->setTitle('Contact Form')
    ->addField('Name', 'text')
    ->addField('Email', 'email')
    ->addField('Message', 'textarea')
    ->addButton('Submit', 'submit')
    ->setAction('/submit-form')
    ->setMethod('POST')
    ->generateForm();

示例5:发送自定义电子邮件假设您正在开发一个用于发送用户自定义电子邮件的应用程序。FluentInterface可以简化这些电子邮件的构建。

__(EmailBuilder::class)
    ->setRecipient('user@example.com')
    ->setSubject('Welcome!')
    ->setBody('Hi, [name]. Thank you for joining our website.')
    ->addAttachment('invoice.pdf')
    ->setSender('info@mycompany.com')
    ->send();

示例6:生成动态SQL查询假设您正在开发一个需要生成动态SQL查询以与数据库交互的Web应用程序。您可以使用FluentInterface编程和可读性地构建这些查询。

$query = __(QueryBuilder::class)
    ->select('name', 'email')
    ->from('users')
    ->where('age', '>', 25)
    ->andWhere('city', '=', 'New York')
    ->orderBy('name', 'ASC')
    ->limit(10)
    ->execute();

示例7:创建交互式图表假设您正在开发一个向用户显示交互式图表的Web应用程序。FluentInterface可以帮助您灵活构建和配置这些图表。

$chart = __(ChartBuilder::class)
    ->setType('line')
    ->setTitle('Monthly Sales')
    ->addData('January', [100, 150, 200, 120])
    ->addData('February', [120, 160, 180, 140])
    ->setXAxisLabels(['Week 1', 'Week 2', 'Week 3', 'Week 4'])
    ->setYAxisLabel('Sales (in thousands)')
    ->render();