亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不將所有內容都包裝到 try/catch 中的情況下處理數據驗證

如何在不將所有內容都包裝到 try/catch 中的情況下處理數據驗證

PHP
Cats萌萌 2021-12-03 18:42:20
有人有一個很好的做法來在插入數據庫之前處理數據驗證,而無需將所有內容都包裝到 try/catch 中嗎?try{    (new DB_table)->put();}catch(User_error $e){    echo "Error: Something could not be validated!";}class DB_table extends DB {    public $name = 'john doe';    public $address = 'tall cedar road 123';    public $email = '[email protected]';    public function put(){        $this->validate_name('name');        $this->validate_address('address');        $this->validate_email('email');        if($this->errors){            throw new User_error();        }        // insert data into database    }}class DB {    protected $errors = [];    protected function validate_name(string $key){        try{            $this->$key = trim($this->$key);            // some validation            throw new Input_error('Name could not be validated');        }        catch(Input_error $e){            $this->errors[$key] = $e->getMessage();        }    }    protected function validate_address(string $key){        try{            $this->$key = trim($this->$key);            // some validation            throw new Input_error('Address could not be validated');        }        catch(Input_error $e){            $this->errors[$key] = $e->getMessage();        }    }    protected function validate_email(string $key){        try{            $this->$key = trim($this->$key);            // some validation            throw new Input_error('E-mail could not be validated');        }        catch(Input_error $e){            $this->errors[$key] = $e->getMessage();        }    }}class Input_error extends Error {}class User_error extends Error {}
查看完整描述

1 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

我會將您的驗證邏輯與您的DB_table課程分開。


您可以創建一個驗證器類,如果驗證了內容,則返回 true/false。


如果你使用一個框架,他們可能已經有了這樣的東西。否則你可以實現自己的并從Laravel 的驗證器中獲得靈感


它是這樣使用的:


public function store(Request $request)

    {

        $validator = Validator::make($request->all(), [

            'title' => 'required|unique:posts|max:255',

            'body' => 'required',

        ]);


        if ($validator->fails()) {

            return redirect('post/create')

                        ->withErrors($validator)

                        ->withInput();

        }


        //if you reached this line, then feel free to insert into DB


查看完整回答
反對 回復 2021-12-03
  • 1 回答
  • 0 關注
  • 172 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號