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 ;
}