0
我在我的魔法getter/setter方法上使用Zend_Filter_Input来验证我的输入并将字段强制转换为我想要的类型。验证部分工作良好,但它就像过滤器根本不触发。这里是我的模型相关的逻辑:Zend_Filter_Input过滤不触发
public function getFilters() {
$filters = array(
'*' => array('StringTrim'),
'email_opt_in' => array('Boolean'),
'admin' => array('Boolean'),
'active' => array('Boolean'),
'phone' => array('Digits'),
'activated' => array('Boolean'),
'id' => array('Int'),
'birthyear' => array('Int'),
'username' => array('StringToLower')
);
return $filters;
}
public function getValidators() {
$validators = array(
'email' => array('EmailAddress'),
'username' => array('Alnum'),
'first' => array('Alpha'),
'last' => array('Alpha'),
'birthyear' => array('Digits'),
'phone' => array('Digits')
);
return $validators;
}
public function __set($name, $value) {
if (!array_key_exists($name,$this->_data)) {
throw new Exception('Unknown property: ' . $name);
}
$input = new Zend_Filter_Input($this->getFilters(), $this->getValidators(), array($name => $value));
if ($input->isValid()) {
if (isset($input->$name)) {
$this->_data[$name] = $input->$name;
} else {
$this->_data[$name] = $value;
}
} else {
throw new Exception('The following fields contain invalid values: ' . implode(',',array_keys($input->getInvalid())));
}
}
然而,输出出来是这样的:
object(MyApp_Model_User)#19 (1) {
["_data:protected"]=>
array(15) {
["id"]=>
string(1) "4"
["email"]=>
string(19) "[email protected]"
["password"]=>
string(32) "594851275f207072b172d7508f037d78"
["username"]=>
string(6) "jdoe"
["first"]=>
string(4) "Joe"
["last"]=>
string(5) "Doe"
["phone"]=>
string(10) "1112223333"
["email_opt_in"]=>
int(1)
["zip"]=>
string(5) "55555"
["birthyear"]=>
string(4) "1984"
["gender"]=>
string(4) "male"
["activated"]=>
int(1)
["date_joined"]=>
string(10) "2008-03-11"
["admin"]=>
string(1) "1"
["active"]=>
string(1) "1"
}
}
很抱歉的长贴,但我觉得这是相关了解的问题。
究竟哪个字段没有正确过滤? – smack0007 2010-01-30 21:52:57
所有这些 - 注意结果变量类型如何都是字符串,而不是转换为过滤器中指定的类型(除了已激活,可能是因为它为空值)。这与用数据库查询拉出原始值相同。 – 2010-01-30 22:58:53
你实际上在你的例子中使用__set()设置$ data数组中的每个变量,还是其中一些来自其他地方?也许你可以显示一些产生var_dump的代码。 – smack0007 2010-01-31 00:17:37