我正在学习magento。我有一个模型,下面给出。从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
?
在构造的前面只有一个下划线:_construct而不是__construct。 –
这是因为在Mage_Core_Block_Template中有一个具有相同名称的函数。 – kaushik
@BennyHill Magento块和模型对象有一个内部'_construct'方法,其功能类似于PHP的本地构造函数。 –