数组传参时验证数组格式 
                            
                                                    
                        
                    
                    
  
                    
                    数组传参时验证数组格式
references
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
}
                        
                        
                                            
          
                    
                    
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: