hyperf / hyperf

🚀 A coroutine framework that focuses on hyperspeed and flexibility. Building microservice or middleware with ease.
https://www.hyperf.io
MIT License
6.05k stars 1.18k forks source link

有没有validate转对象的方法呀? #6907

Open lisqorz opened 5 days ago

lisqorz commented 5 days ago

比如Yii2框架那种。可以通过对象属性访问内容的。 现在都是先写接口文档,已经可以生成对象了,不用再代码里写 $this->inpu('a'),...b,...c这样了。 铁汁们有谁是这样做的,可以分享下吗

limingxinleo commented 5 days ago

你是不是想要这个 https://hyperf.wiki/3.1/#/zh-cn/swagger

lazychanger commented 5 days ago

这个?

<?php
declare(strict_types=1);

namespace App\Component\Validation;

use Hyperf\Context\Context;
use Hyperf\Validation\Request\FormRequest as BaseFormRequest;
use Hyperf\Validation\ValidationRuleParser;

class FormRequest extends BaseFormRequest
{
    protected function buildRequestContextKey(): string
    {
        return 'http.request.' . spl_object_hash($this);
    }

    public function validated(): array
    {
        return Context::getOrSet($this->buildRequestContextKey(), function () {
            return $this->formatData(parent::validated());
        });
    }

    protected function formatData(array $data): array
    {
        $response = (new ValidationRuleParser($data))
            ->explode($this->getRules());

        foreach ($data as $key => $value) {
            [$type] = ValidationRuleParser::parse($response->rules[$key]);
            if ($value === '') {
                $data[$key] = null;
                continue;
            }
            $data[$key] = match (strtolower($type)) {
                'integer' => intval($value),
                'boolean' => boolval($value),
                default => $value
            };

        }

        return $data;
    }

    /**
     * @param $name
     * @return mixed
     */
    public function __get($name)
    {
        $data = $this->validated();

        if (isset($data[$name])) {
            return $data[$name];
        }

        return parent::__get($name);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function __isset(string $name): bool
    {
        return isset($this->validated()[$name]);
    }

}
lisqorz commented 5 days ago

额,就和java spring一样,拿到的就是参数对象,不用每个参数再input获取了

[PostMapping(path: '/system/menu')]

public function create(MenuRequest $params)
{
    $params->id;
    $params->name;
    return $this->menuService->add($params);
}
lazychanger commented 5 days ago

那就是我发的了,你可以用啊。

想要代码提示就用注释


/**
*
* @property-read string $name
*/
class MenuRequest extend FormRequest
{
    public function rules() {
        return [
            'name' => 'string'
        ];
    }
}