PHP code example of qiao520 / swoole-logic

1. Go to this page and download the library: Download qiao520/swoole-logic library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

qiao520 / swoole-logic example snippets


$form = DemoForm::instance($data, true);

$form->setAttributes($data);

use Roers\SwLogic\BaseForm;

class DemoForm extends BaseForm
{
    // 以下是表单属性
    public $name;
    public $email;
    public $age;
    public $sex;
    public $others;
    public $default = 0;

    // 以下是覆盖父类的默认设置
    protected $isAutoTrim = true;   // 开启自动去空格(默认开启)
    protected $defaultRequired = true;   // 开启所有属性为必填(默认未开启)
    protected $defaultErrorMessage = '{attribute}格式错误';  // 覆盖自定义错误提示信息

    /**
     * 定义验证规则
     * @return array
     */
    public function rules()
    {
        return [
            // 验证6到30个字符的字符串
            ['name', 'string', 'min' => 6, 'max' => 30, 'maxMinMessage' => '名字必须在{min}~{max}个字符范围内'],
            // 验证年龄必须是整数
            ['age', 'integer', 'min' => 18, 'max' => 100],
            // 集合验证器,验证性别必须是1或2
            ['sex', 'in', 'in' => [1, 2],],
            // 使用自定义验证器,验证名字不能重复
            ['name', 'validateName'],
            // 还可以这样用,对多个字段用同一个验证器规则
            [['age', 'sex'], 'integer'],
            // 验证邮箱格式,并且必填



// 演示表单类
use Roers\Demo\DemoForm;

// 调试打印函数
function debug($msg) {
    echo $msg, PHP_EOL;
}

// 表单提交的数据
$data = [
    'name' => 'zhongdalong',
    'age' => '31',
    'sex' => '',
];
// 演示默认所有字段为非必填项
$form = DemoForm::instance($data);
if ($form->validate()) {
    $result = $form->handle();
    debug('验证通过,业务处理结果:' . json_encode($result));
} else {
    debug('验证不通过,错误提示信息:' .  $form->getError());
}

debug(str_repeat('-------', 10));

// 演示默认所有字段为必填项
$form = DemoForm::instance($data, true);
if ($form->validate()) {
    $result = $form->handle();
    debug('验证通过,业务处理结果:' . json_encode($result));
} else {
    debug('验证不通过,错误提示信息:' .  $form->getError());
}

debug(str_repeat('-------', 10));


// 演示未成年注册场景
$data['age'] = 17;
$form = DemoForm::instance($data);
if ($form->validate()) {
    $result = $form->handle();
    debug('验证通过,业务处理结果:' . json_encode($result));
} else {
    debug('验证不通过,错误提示信息:' .  $form->getError());
}

debug(str_repeat('-------', 10));


// 演示自定义验证器
$data['age'] = 18;
$data['name'] = 'Roers.cn';
$form = DemoForm::instance($data);
if ($form->validate()) {
    $result = $form->handle();
    debug('验证通过,业务处理结果:' . json_encode($result));
} else {
    debug('验证不通过,错误提示信息:' .  $form->getError());
}

debug(str_repeat('-------', 10));