gpt4 book ai didi

php - 如何将多个表单验证请求链接在一起?

转载 作者:行者123 更新时间:2023-12-05 04:09:56 25 4
gpt4 key购买 nike

在我正在处理的 Laravel 项目中,我想创建一个 API。在该 API 中,每个请求都需要某些 JSON 键。例如。 token 或其他始终需要的字段。我熟悉 Laravel 的表单请求功能,它允许您使用包含验证逻辑数组的 rules 方法轻松创建一个类。但是,我想知道是否有一种方法可以创建一个处理“始终需要”字段的请求类,然后​​连接到另一个包含该端点的特定字段验证的请求类。

例如

// MasterRequest.php
public function rules() {
return [
'api_key' => 'required|exists:users,api_key',
];
}

// ProductRequest.php
public function rules() {
return [
'product_id' => 'required|integer',
];
}

然后某种方式总是在每个 api 路由上调用 MasterRequest 验证,然后为每个路由的独特需求指定请求验证的类型?

这是可行的,还是正确的方法?

最佳答案

这很容易设置,使用 PHP 的 OOP 属性。

最简单的方法(也是显而易见的方法):

让自己成为“始终必填字段的主类”,您也可以将其声明为抽象类。

文件AlwaysRequired.php

abstract class AlwaysRequired extends FormRequest 
{
public function rules() {
return [
'api_key' => 'required|exists:users,api_key',
];
}
}

ProductRequest.php

class ProductRequest extends AlwaysRequired 
{
public function rules() {
return array_merge(parent::rules(),
['product_id' => 'required|integer']);
}
}

php.net 上的数组合并

属性方式:

让自己成为大师类,在其中您将使用“始终需要”的规则声明属性,然后在子类(class)中array_merge(array,...)它(就像上面的例子一样)。

“最难”和最令人困惑的方式,但全自动:

您可以利用魔法函数和 method/property visibility PHP 语言。

再次让自己成为大师类,您将在其中获得 protected property带有 __call() magic method 的规则数组和实现.

Note: You can test code below in interactive shell of PHP $php -a and copy-paste the code.

abstract class A { // Master class
protected $rules = ['abc' => 'required'];

function __call($name, $arg) {
if(method_exists($this, 'rules')){
return array_merge($this->rules, $this->rules());
} else {
//or handle any other method here...
die(var_dump($name, $arg));
}
}
}

class B extends A { //Generic class just like ProductRequest...
protected function rules() { // function must be declared as protected! So its invisible for outside world.
return ['def' => 'required'];
}
}

$b = new B();
var_dump($b->rules());

它是如何工作的?

Laravel 在后台尝试在您指定的请求类(在您的情况下为 ProductRequest)上运行 rules() 方法,将其声明为protected 意味着它不能被调用,除了它自己或另一个 child ,这意味着 __call() 方法被调用而不是在抽象父类中声明。 __call() 方法简单地识别调用者是否想调用不存在的(因为设置了protected 可见性)方法 rules() 如果是所以它将 child 的 rules() 结果与 $rules 合并并返回。


检查正确的 API key 应在 Middleware 中处理.

关于php - 如何将多个表单验证请求链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45197441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com