我想在我的自定义模块中使用魔术方法。

我创建了一个具有不同成员变量(variable1,variable2)的新模型,我想像getVariable1一样获取它们。

我需要如何声明这些成员变量?我能把他们保密吗?我还错过了什么?

我读到的某个地方我需要把它们保存在 $_data['variable1'], ,但这是行不通的。

谢谢!

有帮助吗?

解决方案

魔术方法是通过 Varien_Object 类。

public function __call($method, $args)
{
    switch (substr($method, 0, 3)) {
        case 'get' :
            //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
            //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method);
            return $data;

        case 'set' :
            //Varien_Profiler::start('SETTER: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
            //Varien_Profiler::stop('SETTER: '.get_class($this).'::'.$method);
            return $result;

        case 'uns' :
            //Varien_Profiler::start('UNS: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $result = $this->unsetData($key);
            //Varien_Profiler::stop('UNS: '.get_class($this).'::'.$method);
            return $result;

        case 'has' :
            //Varien_Profiler::start('HAS: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            //Varien_Profiler::stop('HAS: '.get_class($this).'::'.$method);
            return isset($this->_data[$key]);
    }
    throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")");
}

您需要扩展该类或从 Varien_ObjectMage_Core_Model_Abstract 例如。您不需要在模型中定义任何变量或方法,只要您的方法以 get, set, unshas, ,这是假设你希望他们作为魔法方法工作。

所以你可以写这样的东西:

$model = Mage::getModel('namespace_module/sample');
$model->setSomeData('Hello');
echo $model->getSomeData();

如果你这样做 Zend_Debug::dump($model); 您会注意到您的数据存储在 _dataVarien_Object 类。

例子::

object(Namespace_Module_Model_Sample)#128 (7) {
  ["_data":protected] => array(1) {
    ["some_data"] => string(5) "Hello"
  }
  ["_hasDataChanges":protected] => bool(true)
  ["_origData":protected] => NULL
  ["_idFieldName":protected] => NULL
  ["_isDeleted":protected] => bool(false)
  ["_oldFieldsMap":protected] => array(0) {
  }
  ["_syncFieldsMap":protected] => array(0) {
  }
}
许可以下: CC-BY-SA归因
scroll top