Magento - 模型类如何获得资源模型得实例

来源:互联网 发布:淘宝店铺策划 编辑:程序博客网 时间:2024/06/05 19:29
1. etc/config.xml有如下配置
<global>
<models>
<hotel>
<class>Cartz_Hotel_Model</class>
<resourceModel>hotel_mysql4</resourceModel>
</hotel>
<hotel_mysql4>
<class>Cartz_Hotel_Model_Mysql4</class>
<entities>
<room>
<table>rooms</table>
</room>
</entities>
</hotel_mysql4>
</models>
<resources>
<hotel_setup>
<setup>
<module>Cartz_Hotel</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</hotel_setup>
<hotel_write>
<connection>
<use>core_write</use>
</connection>
</hotel_write>
<hotel_read>
<connection>
<use>core_read</use>
</connection>
</hotel_read>
</resources>
</global>
2. 模型类为model/Room.php
<?php
class Cartz_Hotel_Model_Room extends Mage_Core_Model_Abstract{
protected function _construct() {
$this->_init('hotel/room');
}
public function listing(){
$this->_getResource()->findAll();
}
}
?>
3. 相应的资源模型类是model/Mysql4
<?php
class Cartz_Hotel_Model_Mysql4_Room extends Mage_Core_Model_Mysql4_Abstract{
protected function _construct(){
   $this->_init('hotel/room', 'id');
}
public function findAll() {
   $handle = $this->_getWriteAdapter();
   $query = $handle->query('select name from rooms');
   while ($row = $query->fetch()) {
$row = new Varien_Object($row);
      echo $row->getName() . "<br/>";
}
}
}
?>
这段代码昭示了两个知识点:

1. model类的方法_getResource()获得相应资源模型类的实例。
2. 在资源模型类中, 方法 _getWriteAdapter()用来获得数据库的连接句柄

来自: http://hi.baidu.com/pw425/blog/item/9a2a6a1d401ecd8286d6b64d.html
原创粉丝点击