magento核心类Varien_Object
magento所有的数据模型都继承自类“Varien_Object”。这个类属于Magento的系统类库.
你可以在这里找到这个类
lib/Varien/Object.php
Magento模型的数据保存在“_data”属性中,这个属性是“protected”修饰的。父类“Varian_Object”定义了一些函数用来取出这些数据。我们上面的例子用了“getData”,这个方法返回一个数组,数组的元素是“key/value”对。【注:其实就是数据表中一行的数据,“key”就是列名,“value”就是值】我们可以传入一个参数获取某个具体的“key”的值。
$model->getData();
$model->getData('title');
还有一个方法是“getOrigData”,这个方法会返回模型第一次被赋予的值。【注:因为模型在初始化以后,值可以被修改,这个方法就是拿到那个最原始的值】
$model->getOrigData();
$model->getOrigData('title');
getData("xxx")和getXXX的效果是一样的
$customer = new Varien_Object(); $customer->setData( array( 'name' => 'Google', 'email' => 'lonely@gmail.com' ) );
然后我们就可以这样来设置和获取属性值
$customer->getName();
$customer->getEmail();
$customer->getData("name");
$customer->addData("name",value);
$customer->setData("name",value);
$customer['name'];
$customer['name']=value;
上面都是等价的, 是不是很神奇?那继续往下看
“Varien_Object”也实现了一些PHP的特殊函数,比如神奇的“__call”。你可以对任何一个属性调用“get, set, unset, has”方法
/**
* Set/Get attribute wrapper
*
* @param string $method
* @param array $args
* @return mixed
*/
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"中定义的__call函数,通过该函数,只要通过EAV模型加入的新属性,都可以使用getxxx,setXXX等方法...
我爱PHP这个特性,不像java要写一堆的GETTER,Setter,当然学JAVA的兄弟可以看看我这篇文章
使用这些魔术代码..方法名中的属性名字符合“camelcase”命名规则【注:简单的说就是Java的命名规则,每个单词的第一个字母大写,第一个字母可以大写也可以小写】。为了有效的利用这些方便的方法,我们在定义数据表列名的时候要用小写,并用下划线作为分隔符,比如“blogpost_id”。在最近的 Magento版本中,这个规则已经被弱化,为了实现PHP的“ArrayAccess”接口
ArrayAccess接口是在php5中多出来的.
ArrayAccess的作用是使你的Class看起来想一个PHP数组
$id = $model->['blogpost_id']; $model->['blogpost_id'] = 25;
所以在magento中可以使用数组的方式来操作数据模型,当然你也可以使用上面的getxxx
$product['id']; $product->getId();
文章作者:POPO4J
本文地址:http://www.popo4j.com/magento/magento_varien_object.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!