【发布时间】:2012-12-28 09:28:50
【问题描述】:
我正在学习 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;
}
}
在控制器中我使用 validate 方法如下:
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,为什么它没有返回任何值?
【问题讨论】:
-
construct 前面只有一个下划线:_construct 而不是 __construct。
-
这里可行,因为在 Mage_Core_Block_Template 中有一个同名的函数。
-
@BennyHill Magento 块和模型对象有一个内部
_construct方法,其功能类似于 PHP 的原生构造函数。 -
@kaushik,Zend_Debug::dump($this->errors) 的输出是什么?它是预期的数组吗?它是否包含您可以搜索的键?
-
kaushik - 抱歉,我不熟悉 Magento,我不知道 _construct 方法名称。 @AlanStorm - 感谢您指出这一点:-)