input
2.3.1 - PHP 8.1 support
帶有無聊名稱的輸入驗證框架
ChangElog
輸入驗證是任何Web應用程序中的重要任務,但仍然是一項非常繁瑣的任務。這用適當的數據結構替代了相互融合的檢查,該檢查結構清楚地定義了所需的和可選的輸入。
設計圍繞API驅動設計的想法重新啟動,每個API端點都是其自己的對象,但是並不明確要求這種格式
原始輸入將以兩個主要步驟轉換為安全數據:
解析負責將原始輸入字符串轉換為關聯數組。如果您的應用程序是為此構建的,則可以完全跳過此步驟。
驗證是庫中最有用的部分 - 採用一組定義的可選參數及其類型,並將輸入值與規格進行比較。該實施可以防止無效的數據完全傳播;不可能從無效的數據中創建一個SafeInput對象(您的應用程序將使用的對象)!
完成此過程後,將返回一個SafeInput對象,該對象按照實現ValidationInterface的對象定義的規格(缺少可選值為null)。
因為該庫的存在是為了提供可信賴的數據,所以它將積極阻止您第二次猜測;例如,在數據結構上使用isset或empty將引發異常。作者的經驗是,無法信任您的驗證數據的表演是反圖案和代碼氣味。如果您堅持這樣做,這不是適合您的正確工具。強迫這樣的信任往往會阻止文檔除了現實之外撤離。
一個基本示例如下:
some_controller_file.php
<?php
// This would be in its own file
use Firehed Input Interfaces ValidationInterface ;
use Firehed Input Containers SafeInput ;
use Firehed Input Objects as O ;
class Endpoint
implements ValidationInterface {
public function getOptionalInputs () {
return [
' bar ' => new O Text (),
' baz ' => ( new O Text ())-> setDefaultValue ( ' my baz ' ),
];
}
public function getRequiredInputs () {
return [
' foo ' => new O Text (),
];
}
public function execute ( SafeInput $ i ) {
// ... do some magic
// $i['foo'] will be a string
// $i['bar'] will be a string or null, since it was optional
// $i['baz'] will be a string or 'my baz', since it was an optional with a default value
}
} index.php
<?php
// This is the core of your Front Controller
use Firehed Input Containers RawInput ;
use Firehed Input Parsers URLEncoded ;
// The endpoint should be detrmined by your router
$ endpoint = new Endpoint ();
// The parser should be determined by the Content-Type header
$ parser = new URLEncoded ();
try {
$ input = ( new RawInput ( " foo=world " ))
-> parse ( $ parser )
-> validate ( $ endpoint );
$ endpoint -> execute ( $ input );
} catch ( Firehed Input Exceptions InputException $ e ) {
// The input contained invalid data
} catch ( Exception $ e ) {
// Do any logging, error responses, etc.
echo $ e ;
}