Zend Framework使用Extjs进行数据库交互和分页
2011-04-29 00:54 夜雨瞳 阅读(930) 评论(0) 编辑 收藏 举报一、大概思路
1.1、
(备注:具体配置和运行情况参考上篇Ubuntu10.10 Zend FrameWork配置及helloworld显示)
二、数据库
CREATEDATABASEIFNOTEXISTS `text`;
USE `text`;
--
-- Definition of table `text`.`user`
--
DROPTABLEIFEXISTS `text`.`user`;
CREATETABLE `text`.`user` (
`useId` int(11) NOTNULL AUTO_INCREMENT,
`useAccount` varchar(50) DEFAULTNULL,
`useName` varchar(20) DEFAULTNULL,
`useSex` varchar(5) DEFAULTNULL,
`useAddress` varchar(50) DEFAULTNULL,
`useTime` timestampNOTNULLDEFAULTCURRENT_TIMESTAMP,
PRIMARYKEY (`useId`)
) ENGINE=MyISAM AUTO_INCREMENT=10DEFAULT CHARSET=utf8;
--
-- Dumping data for table `text`.`user`
--
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
LOCK TABLES `user` WRITE;
INSERTINTO `text`.`user` VALUES (3,'rubymatlab','zhouyongfeng','boy','guangdong','2011-04-06 11:05:55'),
(4,'xiaohong','xiaohong','girl','henan','2011-04-06 11:05:55'),
(5,'zhanglao','zhanglao','boy','sichuan','2011-04-02 11:05:55'),
(6,'liuxia','liuxia','girl','beijing','2011-04-02 11:05:55'),
(7,'chenming','chenming','boy','xinjiang','2011-04-02 11:05:55'),
(9,'xiaodong','xiaodong','boy','yunnan','2011-04-02 11:05:55');
USE `text`;
--
-- Definition of table `text`.`user`
--
DROPTABLEIFEXISTS `text`.`user`;
CREATETABLE `text`.`user` (
`useId` int(11) NOTNULL AUTO_INCREMENT,
`useAccount` varchar(50) DEFAULTNULL,
`useName` varchar(20) DEFAULTNULL,
`useSex` varchar(5) DEFAULTNULL,
`useAddress` varchar(50) DEFAULTNULL,
`useTime` timestampNOTNULLDEFAULTCURRENT_TIMESTAMP,
PRIMARYKEY (`useId`)
) ENGINE=MyISAM AUTO_INCREMENT=10DEFAULT CHARSET=utf8;
--
-- Dumping data for table `text`.`user`
--
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
LOCK TABLES `user` WRITE;
INSERTINTO `text`.`user` VALUES (3,'rubymatlab','zhouyongfeng','boy','guangdong','2011-04-06 11:05:55'),
(4,'xiaohong','xiaohong','girl','henan','2011-04-06 11:05:55'),
(5,'zhanglao','zhanglao','boy','sichuan','2011-04-02 11:05:55'),
(6,'liuxia','liuxia','girl','beijing','2011-04-02 11:05:55'),
(7,'chenming','chenming','boy','xinjiang','2011-04-02 11:05:55'),
(9,'xiaodong','xiaodong','boy','yunnan','2011-04-02 11:05:55');
三、创建项目ZFExtjs
四、模型Model
4.1、设置数据库连接Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protectedfunction _initDBConnection ()
{
//数据库连接
$params=array('host'=>'localhost','username'=>'root',
'password'=>'123','dbname'=>'text','charset'=>'utf8');
$db= Zend_Db::factory('PDO_MYSQL',$params);
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('db',$db);
}
}
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protectedfunction _initDBConnection ()
{
//数据库连接
$params=array('host'=>'localhost','username'=>'root',
'password'=>'123','dbname'=>'text','charset'=>'utf8');
$db= Zend_Db::factory('PDO_MYSQL',$params);
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('db',$db);
}
}
4.2、为数据库创建可操作的Model层(即输入zf create db-table User user,然后增加自定义函数方法)
<?php
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected$_name='user';
publicfunction getAllUser ($sql)
{
$adapter= Zend_Registry::get('db');
$result=$adapter->query($sql);
return$result;
}
publicfunction getCount($sql)
{
$adapter=Zend_Registry::get('db');
$result=$adapter->fetchOne($sql);
return$result;
}
}
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected$_name='user';
publicfunction getAllUser ($sql)
{
$adapter= Zend_Registry::get('db');
$result=$adapter->query($sql);
return$result;
}
publicfunction getCount($sql)
{
$adapter=Zend_Registry::get('db');
$result=$adapter->fetchOne($sql);
return$result;
}
}
五、控制器Controller
5.1、编写一个showallAction函数方法
<?php
class IndexController extends Zend_Controller_Action
{
publicfunction init ()
{
/* Initialize action controller here */
}
publicfunction indexAction ()
{
// action body
$this->view->content ="Hello World,Welcome to Zend Framework do Well in Extjs";
$this->render();
}
publicfunction showallAction ()
{
$this->_helper->contextSwitch()->initJsonContext();
$this->getResponse()->setHeader('Content-Type','application/json');
$db=new Application_Model_DbTable_User();
//分页取数据
$start=$this->_request->getPost("start");
$limit=$this->_request->getPost("limit");
$sql="select * from user limit ".$start.",".$limit;
$result=$db->getAllUser($sql);
$select=$result->fetchAll();
$sql="select count(useid) as useid from user";
$count=$db->getCount($sql);
echo"{\"totalCount\":".$count.",\"data\":".
Zend_Json::encode($select) ."}";
}
}
class IndexController extends Zend_Controller_Action
{
publicfunction init ()
{
/* Initialize action controller here */
}
publicfunction indexAction ()
{
// action body
$this->view->content ="Hello World,Welcome to Zend Framework do Well in Extjs";
$this->render();
}
publicfunction showallAction ()
{
$this->_helper->contextSwitch()->initJsonContext();
$this->getResponse()->setHeader('Content-Type','application/json');
$db=new Application_Model_DbTable_User();
//分页取数据
$start=$this->_request->getPost("start");
$limit=$this->_request->getPost("limit");
$sql="select * from user limit ".$start.",".$limit;
$result=$db->getAllUser($sql);
$select=$result->fetchAll();
$sql="select count(useid) as useid from user";
$count=$db->getCount($sql);
echo"{\"totalCount\":".$count.",\"data\":".
Zend_Json::encode($select) ."}";
}
}
六、视图View
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>使用Zend Framework实现ExtjsGrid的交互</title>
<link href="ext-3.2.0/resources/css/ext-all.css" rel="stylesheet"
type="text/css"/>
<script src="ext-3.2.0/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="ext-3.2.0/ext-all.js" type="text/javascript"></script>
<script>
Ext.onReady(function() {
Ext.QuickTips.init();
var _start =0;
var _limit =5;
var store =new Ext.data.JsonStore({
root: 'data',
totalProperty: 'totalCount',
url: 'Index/showall',
fields: [
{ name: 'useAccount', type: 'string' },
{ name: 'useName',type:'string' },
{ name: 'useSex' ,type:'string'},
{ name: 'useAddress',type:'string' },
{ name: 'useTime'}
]
});
var grid =new Ext.grid.GridPanel({
frame: true,
title: '学生各科成绩表',
stripeRows: true, //斑马线
store: store,
applyTo: 'app_grid',
trackMouseOver: true,
height: 300,
width: 800,
loadMask: { msg: '正在加载数据,请稍侯……' },
viewConfig: {
forceFit: true
},
columns: [
new Ext.grid.RowNumberer(), //行号
new Ext.grid.CheckboxSelectionModel({ singleSelect: true }),
{ header: '<font size=2>用户帐户</font>', dataIndex: 'useAccount', sortable: true },
{ header: '<font size=2>用户姓名</font>', dataIndex: 'useName', sortable: true },
{ header: '<font size=2>用户性别</font>', dataIndex: 'useSex', sortable: true },
{ header: '<font size=2>用户地址</font>', dataIndex: 'useAddress', sortable: true },
{ header: '<font size=2>注册时间</font>', dataIndex: 'useTime', sortable: true }
],
bbar: new Ext.PagingToolbar({//分页
pageSize: _limit,
store: store,
displayInfo: true, //非要为true,不然不会显示下面的分页按钮
displayMsg: '<font size=2>第 {0} 条到 {1} 条,一共 {2} 条记录</font>',
emptyMsg: "没有记录"
})
});
store.load({ params: { start: _start, limit: _limit} });
})
</script>
</head>
<body>
<div id="app_grid"></div>
<img src="images/door_open.png"></img>
<?=$this->content;?>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>使用Zend Framework实现ExtjsGrid的交互</title>
<link href="ext-3.2.0/resources/css/ext-all.css" rel="stylesheet"
type="text/css"/>
<script src="ext-3.2.0/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="ext-3.2.0/ext-all.js" type="text/javascript"></script>
<script>
Ext.onReady(function() {
Ext.QuickTips.init();
var _start =0;
var _limit =5;
var store =new Ext.data.JsonStore({
root: 'data',
totalProperty: 'totalCount',
url: 'Index/showall',
fields: [
{ name: 'useAccount', type: 'string' },
{ name: 'useName',type:'string' },
{ name: 'useSex' ,type:'string'},
{ name: 'useAddress',type:'string' },
{ name: 'useTime'}
]
});
var grid =new Ext.grid.GridPanel({
frame: true,
title: '学生各科成绩表',
stripeRows: true, //斑马线
store: store,
applyTo: 'app_grid',
trackMouseOver: true,
height: 300,
width: 800,
loadMask: { msg: '正在加载数据,请稍侯……' },
viewConfig: {
forceFit: true
},
columns: [
new Ext.grid.RowNumberer(), //行号
new Ext.grid.CheckboxSelectionModel({ singleSelect: true }),
{ header: '<font size=2>用户帐户</font>', dataIndex: 'useAccount', sortable: true },
{ header: '<font size=2>用户姓名</font>', dataIndex: 'useName', sortable: true },
{ header: '<font size=2>用户性别</font>', dataIndex: 'useSex', sortable: true },
{ header: '<font size=2>用户地址</font>', dataIndex: 'useAddress', sortable: true },
{ header: '<font size=2>注册时间</font>', dataIndex: 'useTime', sortable: true }
],
bbar: new Ext.PagingToolbar({//分页
pageSize: _limit,
store: store,
displayInfo: true, //非要为true,不然不会显示下面的分页按钮
displayMsg: '<font size=2>第 {0} 条到 {1} 条,一共 {2} 条记录</font>',
emptyMsg: "没有记录"
})
});
store.load({ params: { start: _start, limit: _limit} });
})
</script>
</head>
<body>
<div id="app_grid"></div>
<img src="images/door_open.png"></img>
<?=$this->content;?>
</body>
</html>
七、运行效果
八、总结
Zend Framework和Extjs结合方面还不算太难,不过要掌握好可能需要些时间。
九、相关资源
源代码下载:https://files.cnblogs.com/yongfeng/ZFExtjs.zip(Extjs方面采用版本3.2.0的,并不包含在文件夹内,需要大家手动添加)