我有一个小的输入辅助类。
我读了很多静态类不是最好用的。但是我仍然没有理解为什么我不应该使用静态类。我还没那么先进,所以也许我会在以后弄明白。
我之所以成为静态的原因是它不是每次在我的脚本中调用时都是唯一的对象。
我让班级变得静态是一件好事吗?
class Input {
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($input, $source = 'post') {
if($source == 'post' && isset($_POST[$input])) {
return $_POST[$input];
} else if($source == 'get' && isset($_GET[$input])) {
return $_GET[$input];
}
return false;
}
}
编辑:更新了代码
class Input {
private $_get,
$_post;
public function __construct($get, $post) {
$this->_get = $get;
$this->_post = $post;
}
public function exists($type = 'POST') {
switch($type) {
case 'POST':
return (!empty($this->_post)) ? true : false;
break;
case 'GET':
return (!empty($this->_get)) ? true : false;
break;
default:
return false;
break;
}
}
public function get($input, $source = 'POST') {
if($source == 'POST' && isset($this->_post[$input])) {
return $this->_post[$input];
} elseif($source == 'GET' && isset($this->_get[$input])) {
return $this->_get[$input];
}
throw new Exception('Undefined index: ' . $input);
}
}
答案 0 :(得分:1)
仅仅因为你只有一个东西并不意味着它必须是静态的。特别是在单元测试方面,静态类很难处理。
您的班级Input
必须与$_GET
和$_POST
绑定。这意味着您无法在单元测试中使用它。
如果您的课程看起来像这样:
$input = new Input($_GET, $_POST);
即。你给它全局依赖,现在Input
可以进行测试,因为你可以模拟$_GET
和$_POST
的值。
答案 1 :(得分:0)
如果您不想要静态类,可以执行以下操作:
class Input {
private $array;
function __construct($array) {
$this->array = $array;
}
public function exists() {
return isset($this->array);
}
public function get($input) {
if($this->exists() && isset($this->array[$input])) {
return $this->array[$input];
}
return false;
}
}
$get = new Input($_GET);
$value = $get->get('key');
$post = new Input($_POST);
$value = $post->get('key');