每次编写一些php函数或类方法时,最好检查输入参数并抛出异常,或触发错误或警告等......
例如
<?php
function send_email($email, $subject, $body)
{
if (empty($email)) {
throw new InvalidArgumentException('Email should not be empty');
}
if (!is_string($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException('Email format is invalid');
}
if (empty($subject)) {
throw new InvalidArgumentException('Subject should not be empty');
}
if (!is_string($subject)) {
throw new InvalidArgumentException('Subject must be a string');
}
if (empty($body)) {
throw new InvalidArgumentException('Body should not be empty');
}
if (!is_string($body)) {
throw new InvalidArgumentException('Body must be a string');
}
return mail($email, $subject, $body);
}
正如您所看到的,此示例的大部分内容都包含验证代码,而只有一行有用。 如果您想要可靠地保护您的功能,您实际上需要编写大量代码。这很繁琐。
我的问题是 - 有没有人知道轻松验证代码的好方法? 是否有任何库验证取决于PHP-DOC?例如:
<?php
/**
* @param email $email
* @param string $subject
* @param string $body
*/
function send_email($email, $subject, $body)
{
return mail($email, $subject, $body);
}
谢谢。
答案 0 :(得分:5)
纯PHP中最简单的方法是使用断言来简化检查:
class Assert {
public static function isString($var) {
if (!is_string($var)) {
throw new InvalidArgumentException('Argument is not a string');
}
}
}
function foo($string) {
Assert::isString($string);
...
}
你可以通过内省和/或调试回溯来修改它,以便在抛出的异常中包含更多信息。
答案 1 :(得分:3)
我认为没有图书馆这样做,但如果你真的想这样做:
/**
* @param email $email
* @param string $subject
* @param string $body
*/
function send_email($email, $subject, $body)
{
check_arguments(__FUNCTION__, func_get_args());
return mail($email, $subject, $body);
}
所有的乐趣都在check_arguments()
里面,它将解析DocComment并将声明的类型与实际的参数类型相匹配:
function check_arguments($funcName, array $args){
$func = new \ReflectionFunction($funcName);
$docComment = $func->getDocComment();
// parse the comment here into a data structure,
// compare types and throw Exceptions on failure...
}
答案 2 :(得分:1)
看看Non-standard PHP library (NSPL)。使用args module,您可以执行以下操作:
use const \nspl\args\notEmpty;
use const \nspl\args\string;
use function \nspl\args\expects;
use function \nspl\args\expectsAll;
function validEmail($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL) === false
}
function send_email($email, $subject, $body)
{
expectsAll([nonEmpty, string], [$email, $subject, $body]);
expects('validEmail', $email);
return mail($email, $subject, $body);
}