marco-fiset / flute
PHP的高扩展性验证框架
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-28 15:44:29 UTC
README
这是一个极其出色且易于使用的,轻量级且高度可扩展的PHP流畅验证框架。
Flute的流畅接口受到了.NET的FluentValidation的极大启发。
以下是一个简单的示例,帮助您开始
require 'path/to/flute.php'; $validator = new Validator(); $validator->rule_for('first_name')->max_length(100); $p = new Person('John'); $result = $validator->validate($p); if ($result->valid()) { echo 'Valid!'; }
以下验证规则是默认支持的
- NotNull
- NotEmpty
- Required
- MaxLength
- ...(以及更多。您也可以添加自己的规则)
创建自定义验证规则
创建自定义规则非常简单,您甚至不需要修改Validator
类。所有操作都通过魔法命名约定来完成!例如,以下是构建NotEmpty
规则的方式
// The naming is very important here. More on that later. class NotEmptyRule extends Rule // We must extend the Rule abstract class { //We override the condition function to run our own validation logic public function condition($value) { // The $value variable contains the value we need to validate. // For this particular case, it is considered valid if it is // not equal to the empty string. return $value !== ''; } }
一旦您的规则被定义,它必须可由任何已注册的自动加载器发现,以便使它对Validator
类可用。以下是您如何调用它的方式
// Create an instance of the validator $v = new Validator(); $v->rule_for('first_name')->not_empty();
看我是怎么做的?不需要将not_empty()
函数添加到验证器中。对验证器调用任何未知函数都将创建一个以以下约定命名的规则
- 由下划线分隔的每个单词都应首字母大写。
- 删除下划线。
- 在结果字符串末尾附加'Rule'。
所以not_empty
变成了NotEmptyRule
。验证器将实例化一个NotEmptyRule
类,并将其与调用rule_for
时定义的属性名称关联。很简单,对吧?
如果我想要使用参数呢?
非常简单。以下是MaxLengthRule
实现的简要概述。
class MaxLengthRule extends Rule { public function condition($value) { return strlen($value) <= $this->max_length; //W-w-w-wait, what!? Where does max_length come from? } } $v = new Validator(); $v->rule_for('first_name')->max_length(100);
传递给函数定义的任何参数都将注册在args
数组中,顺序与传递给验证器规则的顺序相同。您还可以使用魔法__get
方法访问args,就像我这里使用max_length
一样。如果您再次调用max_length
,它将返回第一次调用时的相同值。当使用多个参数时,它们以传递的顺序传递,每个名称都有自己的参数。
扩展现有规则
您的自定义规则可以扩展现有规则的行为。让我们看看RequiredRule
的实现。
class RequiredRule extends Rule { public function extend() { return array( new NotNullRule(), new NotEmptyRule() ); } }
如您所见,RequiredRule
仅是NotNullRule
和NotEmptyRule
的组合。extend
函数返回一个实例化的规则数组,您想扩展这些规则。condition
函数将在两个规则上调用,并与逻辑and
结合。也就是说,如果任何条件失败,则被视为无效。
就目前而言,这就是全部内容!敬请期待更多精彩功能!