stellarwp / field-conditions
一组可序列化的类,用于处理PHP字段的条件逻辑
Requires
- ext-json: *
Requires (Dev)
- codeception/module-asserts: ^1.0.0
- codeception/module-phpbrowser: ^1.0.0
- lucatume/wp-browser: ^3.0.14
- phpunit/phpunit: ~6.0
This package is auto-updated.
Last update: 2024-08-31 00:36:16 UTC
README
这是一个用于定义和处理字段条件的PHP库。所谓“字段”条件,是指用于一组字段的条件,例如表单。字段条件由字段名、比较运算符、要比较的值以及组合多个条件时使用的逻辑运算符组成。例如
$condition = new FieldCondition('name', '=', 'John', 'and');
如果名为“name”的字段的值等于“John”,则此条件为真。
最后,所有条件都可以序列化为JSON。预期场景是将这些条件传递到前端以在JavaScript中使用。只需使用json_encode()
函数序列化条件或条件集。
安装
建议使用Composer安装此库。为此,请运行以下命令
composer require stellarwp/field-conditions
如果在WordPress中使用,强烈建议您使用Strauss,以避免与其他插件冲突。
配置
该库包括一个Config
类,可用于设置配置选项。目前,唯一的配置是能够覆盖InvalidArgumentException
,以防您需要在此处使用自己的异常。
use StellarWP\FieldConditions\Config; Config::setInvalidArgumentExceptionClass(MyInvalidArgumentException::class);
如何使用
通常,条件将存储在ConditionSet
对象中。该对象跟踪条件并提供方法来确定给定的数据集是否通过条件或失败。
有两种类型的条件
FieldCondition
- 比较字段值与给定值的条件。NestedCondition
- 包含其他条件的条件。
有两种类型的条件集
SimpleConditionSet
- 平坦的字段条件集ComplexConditionSet
- 无限深的字段条件和嵌套条件集
定义你的条件
首先,您需要实例化您的条件集。如果您只想使用不能嵌套的平坦条件集,则使用SimpleConditionSet
。否则,使用ComplexConditionSet
。
然后,您可以将您的条件传递给条件集
use StellarWP\FieldConditions\ComplexConditionSet; use StellarWP\FieldConditions\FieldCondition; use StellarWP\FieldConditions\NestedCondition; use StellarWP\FieldConditions\SimpleConditionSet; $simpleSet = new SimpleConditionSet(); // you can pass conditions here as well $simpleSet ->where('name', '=', 'John') ->and('age', '>', 18) ->or('age', '<', 5); // Logically: name = 'John' AND age > 18 OR (name = 'Jane' AND age > 21) $complexSet = new ComplexConditionSet(); $complexSet ->where('name', '=', 'John') ->and('age', '>', 18) ->or(function(NestedCondition $condition) { $condition ->where('name', '=', 'Jane') ->and('age', '>', 21); });
条件实例也可以传递给where
、and
和or
方法。请注意,条件中的逻辑运算符将被使用的方法覆盖。
$conditionSet = new SimpleConditionSet(); $nestedCondition = new NestedCondition(); $conditionSet ->where(new FieldCondition('name', '=', 'John')); ->and($nestedCondition);
还可以将条件追加到现有的条件集中
$conditionSet = new SimpleConditionSet(); $conditionSet->append( new FieldCondition('name', '=', 'John'), new FieldCondition('age', '>', 18) );
检查值与条件
一旦您有了条件集,您需要将值传递给条件集以检查给定的数据是否通过条件集。
$data = [ 'name' => 'John', 'age' => 19, ]; $simpleSet ->where('name', '=', 'John') ->and('age', '>', 18); $conditionSet->passes($data); // true $conditionSet->fails($data); // false
关于条件中的逻辑运算符(and/or)的说明
可能令人困惑的一件事是条件中的逻辑运算如何工作。考虑以下内容
$conditionSet = new SimpleConditionSet( new FieldCondition('name', '=', 'John'), new FieldCondition('age', '>', 18, 'or') );
从逻辑上讲,这读作“姓名等于John或年龄大于18”。让人觉得奇怪的是,逻辑运算符出现在第二个条件的末尾。这使得它感觉像是将OR应用于第二个条件的末尾。实际上,OR应用于条件的开头。
逻辑运算符应用于条件的开始处,因为逻辑运算应用于当前条件,而不是下一个条件。这就是为什么通常使用 where()
、and()
和 or()
方法来编写集合,这样更自然。
最后,默认的逻辑运算符是 AND,因此只有在使用 OR 时才需要指定逻辑运算符。