本文共 2406 字,大约阅读时间需要 8 分钟。
magento所有的数据模型都继承自类“Varien_Object”。这个类属于Magento的系统类库.
1 | lib/Varien/Object.php |
Magento模型的数据保存在“_data”属性中,这个属性是“protected”修饰的。父类“Varian_Object”定义了一些函数用来取出这些数据。我们上面的例子用了“getData”,这个方法返回一个数组,数组的元素是“key/value”对。【注:其实就是数据表中一行的数 据,“key”就是列名,“value”就是值】我们可以传入一个参数获取某个具体的“key”的值。
1 | $model->getData(); | |
2 | $model->getData('title'); |
还有一个方法是“getOrigData”,这个方法会返回模型第一次被赋予的值。【注:因为模型在初始化以后,值可以被修改,这个方法就是拿到那个最原始的值】
1 | $model->getOrigData(); | |
2 | $model->getOrigData('title'); |
getData("xxx")和getXXX的效果是一样的
1 | $customer = new Varien_Object(); | |
2 | $customer->setData( |
3 | array( | |
4 | 'name' => 'Google', |
5 | 'email' => 'lonely@gmail.com' | |
6 | ) |
7 | ); |
然后我们就可以这样来设置和获取属性值
1 | $customer->getName(); | |
2 | $customer->getEmail(); |
3 | $customer->getData("name"); | |
4 | $customer->addData("name",value); |
5 | $customer->setData("name",value); | |
6 | $customer['name']; |
7 | $customer['name']=value; |
上面都是等价的, 是不是很神奇?那继续往下看
“Varien_Object”也实现了一些PHP的特殊函数,比如神奇的“__call”。你可以对任何一个属性调用“get, set, unset, has”方法
01 | /** | |
02 | * Set/Get attribute wrapper |
03 | * | |
04 | * @param string $method |
05 | * @param array $args | |
06 | * @return mixed |
07 | */ | |
08 | public function __call($method, $args) |
09 | { | |
10 | switch (substr($method, 0, 3)) { |
11 | case 'get' : | |
12 | //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method); |
13 | $key = $this->_underscore(substr($method,3)); | |
14 | $data = $this->getData($key, isset($args[0]) ? $args[0] : null); |
15 | //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method); | |
16 | return $data; |
17 | case 'set' : | |
18 | //Varien_Profiler::start('SETTER: '.get_class($this).'::'.$method); |
19 | $key = $this->_underscore(substr($method,3)); | |
20 | $result = $this->setData($key, isset($args[0]) ? $args[0] : null); |
21 | //Varien_Profiler::stop('SETTER: '.get_class($this).'::'.$method); | |
22 | return $result; |
23 | case 'uns' : | |
24 | //Varien_Profiler::start('UNS: '.get_class($this).'::'.$method); |
25 | $key = $this->_underscore(substr($method,3)); | |
26 | $result = $this->unsetData($key); |
27 | //Varien_Profiler::stop('UNS: '.get_class($this).'::'.$method); | |
28 | return $result; |
29 | case 'has' : | |
30 | //Varien_Profiler::start('HAS: '.get_class($this).'::'.$method); |
31 | $key = $this->_underscore(substr($method,3)); | |
32 | //Varien_Profiler::stop('HAS: '.get_class($this).'::'.$method); |
33 | return isset($this->_data[$key]); | |
34 | } |
35 | throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")"); | |
36 | } |
看看"Varien_Object"中定义的__call函数,通过该函数,只要通过EAV模型加入的新属性,都可以使用getxxx,setXXX等方法...
转载地址:http://jedli.baihongyu.com/