我正在学习magento。我有一个模型,如下所示。
class Kaushikamdotcom_Test_Model_Validator extends Varien_Object {
private $errors = array();
public function validate($_post) {
$validator = new Zend_Validate_NotEmpty();
$validator->setMessages(
array(
Zend_Validate_NotEmpty::IS_EMPTY => "This field cannot be empty"
)
);
if(isset($_post['save'])) {
if(! $validator->isValid($_post['title'])) {
$this->errors['title'] = "This field cannot be empty";
}
if(! $validator->isValid($_post['filename'])) {
$this->errors['filename'] = "This field cannot be empty";
}
}
}
public function getErrors() {
return $this->errors;
}
}
在控制器中,我使用如下验证方法:
public function indexAction() {
$this->loadLayout();
$validator = Mage::getSingleton('test/validator');
if ($this->getRequest()->isPost()) {
$validator->validate($this->getRequest()->getPost());
}
$this->renderLayout();
}
我在块中调用模型(从Mage_Core_Block_Template扩展),如下所示:
public function _construct() {
$this->validator = Mage::getSingleton('test/validator');
$this->errors = $this->validator->getErrors();
parent::_construct();
}
下面的代码给了我返回值
public function getError($_key) {
$errors = $this->validator->getErrors();
return (isset($errors[$_key])) ? $errors[$_key] : '';
}
如果使用以下代码而不是上面的代码,它不会给出任何返回值
public function getError($_key) {
return (isset($this->errors[$_key])) ? $this->errors[$_key] : '';
}
正如我们$this->errors
在构造函数中初始化的那样,为什么它没有返回任何值?