사용자 정의 모듈에서 매직 메소드 사용
-
12-12-2019 - |
문제
내 사용자 정의 모듈에서 Magic Methods를 사용하고 싶습니다.
다양한 멤버 변수(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_Object
좋다 Mage_Core_Model_Abstract
예를 들어.메소드가 다음으로 시작하는 한 모델에서 변수나 메소드를 정의할 필요가 없습니다. get
, set
, uns
그리고 has
, 이는 매직 메소드로 작동하기를 원한다고 가정합니다.
따라서 다음과 같이 작성할 수 있습니다.
$model = Mage::getModel('namespace_module/sample');
$model->setSomeData('Hello');
echo $model->getSomeData();
만약 당신이 Zend_Debug::dump($model);
귀하의 데이터가 다음 위치에 저장되어 있음을 알 수 있습니다. _data
에 선언된 재산 Varien_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) {
}
}
제휴하지 않습니다 magento.stackexchange