Magento
_在Module中访问数据库
假设你已经在完成了系列文章中前面的部分。那么已经有了一个模型文件为model/Room.php,并且etc/config.xml文件的global内容如下:
<global>
<models>
<hotel>
<class>Cartz_Hotel_Model</class>
</hotel>
</models>
</global>
I. 现在修改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>
II. 创建表结构和录入测试数据
create table rooms(id int not null auto_increment, name varchar(100), primary key(id));
insert into rooms values(1,'Royal Room');
insert into rooms values(2,'Standard Room');
III. model/Room.php内容修改如下:
<?php
class Cartz_Hotel_Model_Room extends Mage_Core_Model_Abstract
{
protected function _construct()
{
$this->_init('hotel/room');
}
}
?>- IV. 新建文件model/Mysql4/Room.php
<?php
class Cartz_Hotel_Model_Mysql4_Room extends Mage_Core_Model_Mysql4_Abstract
{
protected function _construct()
{
$this->_init('hotel/room', 'id');
}
}
?>- V. 修改controllers/RoomController.php.
<?php
class Cartz_Hotel_RoomController extends Mage_Core_Controller_Front_Action{
public function loadAction($id = null){
$id= (int) $this->getRequest()->getParam('id', false);
$roomObj = Mage::getModel('hotel/room');$room = $roomObj->load($id);
$name = $room->getName();
if(empty($name)) {
echo "Not Existed Room.";
} else {
echo "Room Name : ".$name;
}
}
}
?>- 当在浏览器地址栏中输入:
http://localhost/magento
/index.php/hotel/room/load/id/1你这是应该看到页面上输出字符串:
Room Name : Royal Room这里还揭示了页面参数是如何传给Magento
的Controller里的:
url上的id/1在action方法中用
$this->getRequest()->getParam('id', false);
来获取.