カスタムモジュールでマジックメソッドを使用してください
-
12-12-2019 - |
質問
私のカスタムモジュールのマジックメソッドを利用したいです。
私は異なるメンバー変数(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