数组传参时验证数组格式

数组传参时验证数组格式

references

www.php.net/manual/zh/class.arraya...

表单验证《Laravel 8 中文文档》

function test (array $arr)
{
    ......
}

比如上面的函数接收数组类型的参数,希望参数 $arr 符合一定的格式,比如必须有 name 做为 key

$arr = [
    'name' => 'zhangsan'
];

定义一个类实现 (数组式访问)接口

<?php

namespace App\Services\Pay\Sdk;

use App\Exceptions\Pay\InvalidArgumentException;
use Illuminate\Support\Facades\Validator;

class PreOrderParams implements \ArrayAccess
{
    protected $data = [];

    protected $rules = [
        'money' => 'required',
        'detail' => 'required',
        'no' => 'required',
        'ip' => 'required',
    ];

    public function __construct($data)
    {
        $this->data = $data;
        $this->validate();
    }

    protected function validate()
    {
        $validator = Validator::make($this->data, $this->rules);

        if ($validator->fails()) {
            throw new InvalidArgumentException($validator->errors()->first());
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetGet($offset)
    {
        return $this->data[$offset];
    }

    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }
}

使用

use App\Services\Pay\Sdk\PreOrderParams;

$params = array (
            'detail' => '支付中心-付费商品',
            'pay_money' => '392.01',
            'no' => '20210407151805155245',
            'ip' => '127.0.0.1',
        );
$preOrderParams = new PreOrderParams($params);
test($preOrderParams);

function test (PreOrderParams $preOrderParams)
{
    echo $preOrderParams['no']; // 20210407151805155245
}
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!