私はマジェントを学んでいます。以下に示すモデルがあります。
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
したのに、値が返されないのはなぜですか?