国产+高潮+在线,国产 av 仑乱内谢,www国产亚洲精品久久,51国产偷自视频区视频,成人午夜精品网站在线观看

讓webman和laravel一樣實(shí)現(xiàn)自動(dòng)表單驗(yàn)證

lpz

從laravel轉(zhuǎn)到webman發(fā)現(xiàn)表單驗(yàn)證不能使用依賴注入自動(dòng)驗(yàn)證所以改造了一下。

實(shí)現(xiàn)思路

1、創(chuàng)建一個(gè)BaseValidate基類,基類繼承app\validate,校驗(yàn)類繼承基類
2、在基類的構(gòu)造方法里調(diào)用check方法,這樣在依賴注入的時(shí)候就會(huì)自動(dòng)進(jìn)行校驗(yàn),校驗(yàn)失敗拋出異常
3、在異常處理類中接住,并自定義響應(yīng)

BaseValidate基類代碼

<?php
declare (strict_types=1);

namespace app\validate;

use think\Validate;

class BaseValidate extends Validate
{

    public function __construct() {
        if ($this->scene){
            $scene = request()->action;
            if (!$this->hasScene($scene)){
                return;
            }
            $this->scene($scene);
        }
        $this->failException()->check(request()->all());
    }

}

校驗(yàn)類代碼

<?php
declare (strict_types=1);

namespace app\validate;

use app\validate\BaseValidate;

class TestValidate extends BaseValidate
{

    protected $rule = [
        'name' => 'require',
        'age'  => 'require',
    ];

    protected $message = [
        'name.require' => '名稱必須',
        'age.require'  => '年齡必須',
    ];

    protected $scene = [
        'edit' => ['name'],
        'del' => ['age'],
    ];

}

異常處理類代碼

<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.wtbis.cn/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace support\exception;

use think\exception\ValidateException;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * Class Handler
 * @package support\exception
 */
class Handler extends ExceptionHandler
{
    public $dontReport = [
        BusinessException::class,
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception): Response
    {
        if ($exception instanceof ValidateException) {
            return json([
                'code' => 500,
                'msg' => $exception->getMessage(),
                'data' => null
            ]);
        }
        if(($exception instanceof BusinessException) && ($response = $exception->render($request)))
        {
            return $response;
        }

        return parent::render($request, $exception);
    }

}

控制器調(diào)用(1)

<?php

namespace app\controller;

use app\validate\TestValidate;

class IndexController
{

    public function edit(TestValidate $validate)
    {
        return 'edit';
    }

    public function del(TestValidate $validate)
    {
        return 'del';
    }

}

控制器調(diào)用(2)

<?php

namespace app\controller;

use app\validate\TestValidate;

class IndexController
{

    public function __construct()
    {
        new TestValidate();
    }

    public function index()
    {
        return 'index';
    }

    public function edit()
    {
        return 'edit';
    }

    public function del()
    {
        return 'del';
    }

}

測(cè)試

截圖
截圖
截圖
截圖
截圖

549 2 1
2個(gè)評(píng)論

tuhrx

看了你的代碼,立馬看了Controller初始化的代碼,其實(shí)我的想法跟你的一樣,我是在request對(duì)象初始化那一塊鉆了牛角尖。非常感謝分享!?。??

貼上我的實(shí)現(xiàn):
我用的是 respect/validation 庫(kù)

<?php
declare(strict_types=1);

namespace app\requests;

use Respect\Validation\Exceptions\ValidationException;

class FormRequest
{
    protected array $rules = [];
    protected array $messages = [];
    protected array $data = [];
    private \Webman\Http\Request|\support\Request|null $request;

    public function rules(): array {
        return [];
    }

    public function messages(): array {
        return [];
    }

    /**
     * @throws \app\Exceptions\ValidationException
     */
    public function __construct() {
        $this->request = request();
        $this->data = $this->all();
        $this->validateResolved();
    }

    /**
     * @return void
     * @throws \app\Exceptions\ValidationException
     */
    public function validate(): void
    {
        $this->rules = $this->rules();
        $this->messages = $this->messages();

        $errors = [];

        foreach ($this->rules as $field => $rule) {
            try {
                $rule->assert($this->data[$field] ?? null);
            } catch (ValidationException $exception) {
                $errors[$field] = $exception->getMessages($this->messages[$field] ?? []);
            }
        }

        if (!empty($errors)) {
            throw new \app\Exceptions\ValidationException($errors);
        }
    }

    /**
     * 解析時(shí)自動(dòng)驗(yàn)證
     * @throws \app\Exceptions\ValidationException
     */
    public function validateResolved(): void
    {
        $this->validate();
    }

    public function __call($method, $arguments) {
        if (method_exists($this->request, $method)) {
            return call_user_func_array([$this->request, $method], $arguments);
        }
        throw new \Exception("Method $method does not exist");
    }

    public function __get($name) {
        if (property_exists($this->request, $name)) {
            return $this->request->$name;
        }
        throw new \Exception("Property $name does not exist");
    }

    public function __set($name, $value) {
        if (property_exists($this->request, $name)) {
            $this->request->$name = $value;
        } else {
            throw new \Exception("Property $name does not exist");
        }
    }

    public function __isset($name) {
        return isset($this->request->$name);
    }

    public function __unset($name) {
        unset($this->request->$name);
    }
}
  • 暫無(wú)評(píng)論
tanhongbin

和寫在中間件 有一曲同工之妙

  • 暫無(wú)評(píng)論

lpz

220
積分
0
獲贊數(shù)
0
粉絲數(shù)
2022-09-22 加入
??