承接 web-complete/form 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

web-complete/form

Composer 安装命令:

composer require web-complete/form

包简介

Form model

README 文档

README

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version License

Flexible filtration and validation server side Form Model like in Yii2.

The library has no dependencies and can be easily used with any frameworks or code.

Installation

composer require web-complete/form

Usage

To use the Form, you need to create a class which extend AbstractForm and implement abstract methods: rules () and filters (). In the primitive case, they can return empty arrays.

Filters (filtration rules) is an array of the following format:

[
    [field, filter, params]
]

where:

field - field name or field path (dot separated) or array of fields
filter - filter name. It can be a string or callable function. The Form will check method availability in the own object and if not exists then in filter objects array (filtersObject) in case of string. The filter will be called with arguments: $value, $params (parameters from the filtration rules), $form (current from object) and will return the filtered value.
params - array of parameters will be passed to the filter. The requirement depends on the called filter.

Rules (validation rules) is an array of the following format:

[
    [field, validator, params, message]
]

where:

field - field name or field path (dot separated) or array of fields
validator - validator name. It can be a string or callable function. It can be a string or callable function. The Form will check method availability in the own object and if not exists then in validator objects array (validatorsObject) in case of string. The validator will be called with arguments: $value and $params (parameters from the filtration rules) and will return boolean.
params - array of parameters will be passed to the filter. The requirement depends on the called filter.
message - Message in case of error. Returns "error" by default or value from overridden the $defaultError property.

If the data field does not have any filtering or validation rules, it will be deleted. However, if the field is necessary, but does not require filtering and validation, you can specify its security by adding it to the rules rules without additional arguments:

[
    ['name', 'string', ['min' => 3]],
    ['data.nested.field', 'string', ['min' => 3]],
    ['age'], // this field is considered as safe
]

The form has a built-in validator required, which checks that this field is not empty. The other validators will only be applied to non-empty fields.

The class constructor takes the following arguments:

    public function __construct(
        $rules = null,
        $filters = null,
        $validatorsObject = null,
        $filtersObject = null
    )

rules - will be merged with rules() (optional)
filters - will be merged with filters() (optional)
validatorsObject - object with validation methods (optional)
filtersObject - object with filtration methods (optional)

The form API provides the following methods:

validate() : - validate data
setData($data) - filter and set form data
getData() - get form data
setValue($field, $value, $filter = true) - filter (by default) and set form field value
getValue($field) - get form field value
addError($field, $error) - add an error for field
hasErrors($field = null) - check for errors in the form or field
getErrors($field = null) - get form or field errors
getFirstErrors() - get the first errors of all form fields
resetErrors() - reset form errors

This library has classes Validators and Filters which contains the most commonly used filters and validators and FastForm class form simple forms.

Filters

Filters supplied with the library (can be used independently):

trim - trim spaces (arguments: charlist, left, right)
escape - htmlspecialchars
capitalize - transform string to lowercase and capitalize first char
lowercase - transform string to lowercase
uppercase - transform string to uppercase
replace - replace substring (optional arguments: pattern (string or regular expression), to)
stripTags - strip html-tags
stripJs - strip js

For more information, see the Filters class annotations

Validators

Validators supplied with the library (can be used independently):

equals - comparison with other value (arguments: value, not (check inequality in case of true))
compare - comparison with other value (arguments: field (The third argument is the Form object), not (check inequality in case of true))
email - e-mail
number - validate if numeric (optional arguments: min, max)
string - validate if string (optional arguments: min, max - string length)
regex - regular expression (arguments: pattern)

For more information, see the Validators class annotations

Examples

Filtering and validation rules:

class MyForm1 extends \WebComplete\form\AbstractForm
{
    
    protected function filters()
    {
        return [
            [['first_name', 'last_name'], 'capitalize'],
            ['description', 'stripTags'],
            ['content', 'stripJs'],
            ['data.nested.field', 'trim'],
            ['email', 'replace', ['pattern' => 'email.com', 'to' => 'gmail.com']],
            ['*', 'trim'],
        ];
    }

    protected function rules()
    {
        return [
            [['description', 'label'], ], // safe fields (no validation)
            [['name', 'email'], 'required', [], 'Field is required'],
            ['name', 'string', ['min' => 2, 'max' => 50], 'Incorrect name'],
            ['email', 'email', [], 'Incorrect email'],
            ['price', 'validatePrice'],
            ['password', 'required'],
            ['password_repeat', 'compare', ['field' => 'password'], 'Repeat password error'],
            ['data.token', 'validateToken'],
            ['some', [SomeValidator::class, 'method'], ['customParam' => 100], 'Incorrect'],
            [['*'], 'regex', ['pattern' => '/^[a-z]$/'], 'Field is required'],
        ];
    }
    
    protected function validatePrice($value, $params, AbstractForm $form)
    {
        ...
        return true;
    }
    
    protected function validateToken($value, $params, AbstractForm $form)
    {
        ...
        return true;
    }
    
}

Form usage:

$form = new MyForm([], [], new Validators(), new Filters());
$form->setData($_POST);
if($form->validate()) {
    $filteredData = $form->getData();
    ...
}

Fast Form usage:

$form = new FastForm([['name', 'required'], ['email', 'email']]);
$form->setData($_POST);
if($form->validate()) {
    $filteredData = $form->getData();
    ...
}
else {
    $form->getErrors();
//    $form->getErrors('name');
//    $form->getFirstErrors();
//    $form->hasErrors();
    ...
}

Custom abstract form creation with default rules:

abstract class MyAbstractForm extends \WebComplete\form\AbstractForm
{

    protected function filters()
    {
        return [
            ['*', 'trim'] 
        ];
    }

    public function __construct($rules = [], $filters = [])
    {
        parent::__construct($rules, $filters, new Validators(), new Filters();
    }
    
}

web-complete/form 适用场景与选型建议

web-complete/form 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 854 次下载、GitHub Stars 达 0, 最近一次更新时间为 2017 年 09 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「form」 「model」 「yii」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 web-complete/form 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 web-complete/form 我们能提供哪些服务?
定制开发 / 二次开发

基于 web-complete/form 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 854
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-09-18