写给准备使用ZendFramework的同学
经过两个月的艰难学习,php终于玩上手了,多亏有Zend frameword才完成手里面这个项目,虽然以前是做.Net的,感觉PHP还是一门很容易上手的脚本语言,拿来做Web很是爽,今天抽空做了一个示例 程序,这个小程序演示了如何使用Zend Frameword构建一个基本的程序框架. 程序很简单就一个任务列表管理, 包括了常见的CRUD操作, 除了可以学习一些常见操作外,我还附带一些通用组件,帮助大家在以后的开发中参考使用, 如果对ZF的使用有问题可以参照官方网站的文档资料和ZF的API,一般有这两个东西基本可以解决所有的问题了:
1. 一个可以在ZF中工作的分页控件
2. 一个通用的单例程序.
3. 一个基于 MyGeneration的代码生成模版,可以对数据库里面表直接进行映射,不用写一行代码就可以方便地调用数据. 目前 支持单表数据查询,联各主键, 生成的方法包括 按主键查找,添加,修改,删除,分页查询,计数,如果表中包含索引,将自动生成按索引查找的方法,把大家从书写sql语句的痛苦中解胶出来, 比如在name例上建立索引将在model层生成 get_IX_name($name......)的方法. 稍作扩展还可以支持外键方法生成,视图映射等等,有兴趣的可以看帮助自己动手,也不难. 这部分的内容原是联想到了.netTiers 里面的实现而加上的, 这部分数据访问的代码本来都差不多,就不用多次重写了.
另外需要说明的是,如果你希望表映身过来的时候使用别名可以使用 mygeneration 的mymeta browser, 通过local meta data mappings指定相关表的别名
OK,有了这些东西我们就可以制作一个可以兼容多种数据库的应用程序了
下面附上以上三个东西的代码
<?php
/**
* class for load singleton instance, support Model and DbTable. classes.
*
*/
class tc_Singleton
{
/**
* load instance.
*/
public static function getInstance ($class)
{
static $instances = array(); // array of instance names
if (! array_key_exists($class, $instances)) {
// instance does not exist, so create it
// m_name(Model Class) or t_name(Db Table Class)
$path = explode('_', $class);
$file_name = $path[1];
$class_name= '';
if ($path[0] == 'm') {
$class_name = 'Model_' . $file_name;
require_once APPLICATION_PATH . '/models/' . $file_name . '.php';
}
if ($path[0] == 't') {
$class_name = 'Model_DbTable_' . $file_name;
require_once APPLICATION_PATH . '/models/DbTable/' . $file_name . '.php';
}
//$instances[$class] = & new $path[1]();
$instances[$class] = new $class_name();
} // if
$instance = & $instances[$class];
return $instance;
}
}
?>
ZF分页控件
1. 一个可以在ZF中工作的分页控件
2. 一个通用的单例程序.
3. 一个基于 MyGeneration的代码生成模版,可以对数据库里面表直接进行映射,不用写一行代码就可以方便地调用数据. 目前 支持单表数据查询,联各主键, 生成的方法包括 按主键查找,添加,修改,删除,分页查询,计数,如果表中包含索引,将自动生成按索引查找的方法,把大家从书写sql语句的痛苦中解胶出来, 比如在name例上建立索引将在model层生成 get_IX_name($name......)的方法. 稍作扩展还可以支持外键方法生成,视图映射等等,有兴趣的可以看帮助自己动手,也不难. 这部分的内容原是联想到了.netTiers 里面的实现而加上的, 这部分数据访问的代码本来都差不多,就不用多次重写了.
另外需要说明的是,如果你希望表映身过来的时候使用别名可以使用 mygeneration 的mymeta browser, 通过local meta data mappings指定相关表的别名
OK,有了这些东西我们就可以制作一个可以兼容多种数据库的应用程序了
下面附上以上三个东西的代码
通用单例程序: 可以减少对象创建带来的开销.
Code
<?php
/**
* class for load singleton instance, support Model and DbTable. classes.
*
*/
class tc_Singleton
{
/**
* load instance.
*/
public static function getInstance ($class)
{
static $instances = array(); // array of instance names
if (! array_key_exists($class, $instances)) {
// instance does not exist, so create it
// m_name(Model Class) or t_name(Db Table Class)
$path = explode('_', $class);
$file_name = $path[1];
$class_name= '';
if ($path[0] == 'm') {
$class_name = 'Model_' . $file_name;
require_once APPLICATION_PATH . '/models/' . $file_name . '.php';
}
if ($path[0] == 't') {
$class_name = 'Model_DbTable_' . $file_name;
require_once APPLICATION_PATH . '/models/DbTable/' . $file_name . '.php';
}
//$instances[$class] = & new $path[1]();
$instances[$class] = new $class_name();
} // if
$instance = & $instances[$class];
return $instance;
}
}
?>
Code
<?
class tc_Pager
{
private $_navigationItemCount = 10; //导航栏显示导航总页数
private $_pageSize = null; //每页项目数
private $_align = "right"; //导航栏显示位置
private $_itemCount = 0; //总项目数
private $_pageCount = 0; //总页数
private $_currentPage = null; //当前页
private $_front = null; //前端控制器
private $_PageParaName = "p"; //页面参数名称
private $_firstPageString = "|<<"; //导航栏中第一页显示的字符
private $_nextPageString = ">>"; //导航栏中前一页显示的字符
private $_previousPageString = "<<"; //导航栏中后一页显示的字符
private $_lastPageString = ">>|"; //导航栏中最后一页显示的字符
private $_splitString = " | ";
//add by maxiao 是否使用 modele
private $_isUsingModule = 0;//默认是不使用的.
//页数字间的间隔符 /
public function __construct($itemCount, $pageSize,$isUsingModule = 0)//add by ma
{
//add by ma
$_isUsingModule = $isUsingModule;
if(!is_numeric($itemCount) || (!is_numeric($pageSize)))
throw new Exception("Pagination Error:not Number");
$this->_itemCount = $itemCount;
$this->_pageSize = $pageSize;
$this->_front = Zend_Controller_Front::getInstance();
$this->_pageCount = ceil($itemCount/$pageSize); //总页数
$page = $this->_front->getRequest()->getParam($this->_PageParaName);
if(empty($page) || (!is_numeric($page))) //为空或不是数字,设置当前页为1
{
$this->_currentPage = 1;
}
else
{
if($page < 1)
$page = 1;
if($page > $this->_pageCount)
$page = $this->_pageCount;
$this->_currentPage = $page;
}
}
/**
* 返回当前页
* @param int 当前页
*/
public function getCurrentPage()
{
return $this->_currentPage;
}
/**
* 返回导航栏目
* @return string 导航html class="PageNavigation"
*/
public function getNavigation()
{
$navigation = '<div style="text-align:'.$this->_align.'">';
$pageCote = ceil($this->_currentPage / ($this->_navigationItemCount - 1)) - 1; //当前页处于第几栏分页
$pageCoteCount = ceil($this->_pageCount / ($this->_navigationItemCount - 1)); //总分页栏
$pageStart = $pageCote * ($this->_navigationItemCount -1) + 1; //分页栏中起始页
$pageEnd = $pageStart + $this->_navigationItemCount - 1; //分页栏中终止页
if($this->_pageCount < $pageEnd)
{
$pageEnd = $this->_pageCount;
}
$navigation .= "总共:{$this->_itemCount}条 {$this->_pageCount}页\n";
if($pageCote > 0 && $this->_pageCount >1) //首页导航
{
$navigation .= '<a href="'.$this->createHref(1)."\">$this->_firstPageString</a> ";
}
if($this->_currentPage != 1 && $this->_pageCount >1) // 上一页导航
{
$navigation .= '<a href="'.$this->createHref($this->_currentPage-1);
$navigation .= "\">$this->_previousPageString</a> ";
}
while ($pageStart <= $pageEnd && amp; $this->_pageCount >1) // 构造数字导航区
{
if($pageStart == $this->_currentPage)
{
$navigation .= "<strong>$pageStart</strong>".$this->_splitString;
}
else
{
$navigation .= '<a href="'.$this->createHref($pageStart)."\">$pageStart</a>".$this->_splitString;
}
$pageStart++;
}
if($this->_currentPage != $this->_pageCount && $this->_pageCount >1) //下一页导航
{
$navigation .= ' <a href="'.$this->createHref($this->_currentPage+1)."\">$this->_nextPageString</a> ";
}
if($pageCote < $pageCoteCount-1 && $_pageCount > 1 ) // 未页导航
{
$navigation .= '<a href="'.$this->createHref($this->_pageCount)."\">$this->_lastPageString</a> ";
}
//添加直接导航框
//$navigation .= '<input type="text" size="3" onkeydown="if(event.keyCode==13){window.location=\' ';
//$navigation .= $this->createHref().'\'+this.value;return false;}" />';
//2008年8月27号补充输入非正确页码后出现的错误——begin
$navigation .= ' <select onchange="window.location=\' '.$this->createHref().'\'+this.options[this.selectedIndex].value;">';
for ($i=1;$i<=$this->_pageCount;$i++){
if ($this->getCurrentPage()==$i){
$selected = "selected";
}
else {
$selected = "";
}
$navigation .= '<option value='.$i.' '.$selected.'>'.$i.'</option>';
}
$navigation .= '</select>';
//2008年8月27号补充输入非正确页码后出现的错误——end
$navigation .= "</div>";
return $navigation;
}
/**
* 取得导航栏显示导航总页数
*
* @return int 导航栏显示导航总页数
*/
public function getNavigationItemCount()
{
return $this->_navigationItemCount;
}
/**
* 设置导航栏显示导航总页数
*
* @param int $navigationCount: 导航栏显示导航总页数
*/
public function setNavigationItemCoun($navigationCount)
{
if(is_numeric($navigationCount))
{
$this->_navigationItemCount = $navigationCount;
}
}
/**
* 设置首页显示字符
* @param string $firstPageString 首页显示字符
*/
public function setFirstPageString($firstPageString)
{
$this->_firstPageString = $firstPageString;
}
/**
* 设置上一页导航显示字符
* @param string $previousPageString: 上一页显示字符
*/
public function setPreviousPageString($previousPageString)
{
$this->_previousPageString = $previousPageString;
}
/**
* 设置下一页导航显示字符
* @param string $nextPageString:下一页显示字符
*/
public function setNextPageString($nextPageString)
{
$this->_nextPageString = $nextPageString;
}
/**
* 设置未页导航显示字符
* @param string $nextPageString:未页显示字符
*/
public function setLastPageString($lastPageString)
{
$this->_lastPageString = $lastPageString;
}
/**
* 设置导航字符显示位置
* @param string $align:导航位置
*/
public function setAlign($align)
{
$align = strtolower($align);
if($align == "center")
{
$this->_align = "center";
}elseif($align == "right")
{
$this->_align = "right";
}else
{
$this->_align = "left";
}
}
/**
* 设置页面参数名称
* @param string $pageParamName:页面参数名称
*/
public function setPageParamName($pageParamName)
{
$this->_PageParaName = $pageParamName;
}
/**
* 获取页面参数名称
* @return string 页面参数名称
*/
public function getPageParamName()
{
return $this->_PageParaName;
}
/**
* 生成导航链接地址
* @param int $targetPage:导航页
* @return string 链接目标地址
*/
private function createHref($targetPage = null)
{
$params = $this->_front->getRequest()->getParams();
$module = $params["module"];
$controller = $params["controller"];
$action = $params["action"];
//add by ma
if($this->_isUsingModule == 0)
$targetUrl = $this->_front->getBaseUrl()."/$controller/$action";
else
$targetUrl = $this->_front->getBaseUrl()."/$module/$controller/$action";
foreach ($params as $key => $value)
{
if($key != "controller" && $key != "module" && $key != "action" && $key != $this->_PageParaName)
{
$targetUrl .= "/$key/$value";
}
}
if(isset($targetPage)) // 指定目标页
$targetUrl .= "/$this->_PageParaName/$targetPage";
else
$targetUrl .= "/$this->_PageParaName/";
return $targetUrl;
}
}
?>
MyGeneration的生成模版:<?
class tc_Pager
{
private $_navigationItemCount = 10; //导航栏显示导航总页数
private $_pageSize = null; //每页项目数
private $_align = "right"; //导航栏显示位置
private $_itemCount = 0; //总项目数
private $_pageCount = 0; //总页数
private $_currentPage = null; //当前页
private $_front = null; //前端控制器
private $_PageParaName = "p"; //页面参数名称
private $_firstPageString = "|<<"; //导航栏中第一页显示的字符
private $_nextPageString = ">>"; //导航栏中前一页显示的字符
private $_previousPageString = "<<"; //导航栏中后一页显示的字符
private $_lastPageString = ">>|"; //导航栏中最后一页显示的字符
private $_splitString = " | ";
//add by maxiao 是否使用 modele
private $_isUsingModule = 0;//默认是不使用的.
//页数字间的间隔符 /
public function __construct($itemCount, $pageSize,$isUsingModule = 0)//add by ma
{
//add by ma
$_isUsingModule = $isUsingModule;
if(!is_numeric($itemCount) || (!is_numeric($pageSize)))
throw new Exception("Pagination Error:not Number");
$this->_itemCount = $itemCount;
$this->_pageSize = $pageSize;
$this->_front = Zend_Controller_Front::getInstance();
$this->_pageCount = ceil($itemCount/$pageSize); //总页数
$page = $this->_front->getRequest()->getParam($this->_PageParaName);
if(empty($page) || (!is_numeric($page))) //为空或不是数字,设置当前页为1
{
$this->_currentPage = 1;
}
else
{
if($page < 1)
$page = 1;
if($page > $this->_pageCount)
$page = $this->_pageCount;
$this->_currentPage = $page;
}
}
/**
* 返回当前页
* @param int 当前页
*/
public function getCurrentPage()
{
return $this->_currentPage;
}
/**
* 返回导航栏目
* @return string 导航html class="PageNavigation"
*/
public function getNavigation()
{
$navigation = '<div style="text-align:'.$this->_align.'">';
$pageCote = ceil($this->_currentPage / ($this->_navigationItemCount - 1)) - 1; //当前页处于第几栏分页
$pageCoteCount = ceil($this->_pageCount / ($this->_navigationItemCount - 1)); //总分页栏
$pageStart = $pageCote * ($this->_navigationItemCount -1) + 1; //分页栏中起始页
$pageEnd = $pageStart + $this->_navigationItemCount - 1; //分页栏中终止页
if($this->_pageCount < $pageEnd)
{
$pageEnd = $this->_pageCount;
}
$navigation .= "总共:{$this->_itemCount}条 {$this->_pageCount}页\n";
if($pageCote > 0 && $this->_pageCount >1) //首页导航
{
$navigation .= '<a href="'.$this->createHref(1)."\">$this->_firstPageString</a> ";
}
if($this->_currentPage != 1 && $this->_pageCount >1) // 上一页导航
{
$navigation .= '<a href="'.$this->createHref($this->_currentPage-1);
$navigation .= "\">$this->_previousPageString</a> ";
}
while ($pageStart <= $pageEnd && amp; $this->_pageCount >1) // 构造数字导航区
{
if($pageStart == $this->_currentPage)
{
$navigation .= "<strong>$pageStart</strong>".$this->_splitString;
}
else
{
$navigation .= '<a href="'.$this->createHref($pageStart)."\">$pageStart</a>".$this->_splitString;
}
$pageStart++;
}
if($this->_currentPage != $this->_pageCount && $this->_pageCount >1) //下一页导航
{
$navigation .= ' <a href="'.$this->createHref($this->_currentPage+1)."\">$this->_nextPageString</a> ";
}
if($pageCote < $pageCoteCount-1 && $_pageCount > 1 ) // 未页导航
{
$navigation .= '<a href="'.$this->createHref($this->_pageCount)."\">$this->_lastPageString</a> ";
}
//添加直接导航框
//$navigation .= '<input type="text" size="3" onkeydown="if(event.keyCode==13){window.location=\' ';
//$navigation .= $this->createHref().'\'+this.value;return false;}" />';
//2008年8月27号补充输入非正确页码后出现的错误——begin
$navigation .= ' <select onchange="window.location=\' '.$this->createHref().'\'+this.options[this.selectedIndex].value;">';
for ($i=1;$i<=$this->_pageCount;$i++){
if ($this->getCurrentPage()==$i){
$selected = "selected";
}
else {
$selected = "";
}
$navigation .= '<option value='.$i.' '.$selected.'>'.$i.'</option>';
}
$navigation .= '</select>';
//2008年8月27号补充输入非正确页码后出现的错误——end
$navigation .= "</div>";
return $navigation;
}
/**
* 取得导航栏显示导航总页数
*
* @return int 导航栏显示导航总页数
*/
public function getNavigationItemCount()
{
return $this->_navigationItemCount;
}
/**
* 设置导航栏显示导航总页数
*
* @param int $navigationCount: 导航栏显示导航总页数
*/
public function setNavigationItemCoun($navigationCount)
{
if(is_numeric($navigationCount))
{
$this->_navigationItemCount = $navigationCount;
}
}
/**
* 设置首页显示字符
* @param string $firstPageString 首页显示字符
*/
public function setFirstPageString($firstPageString)
{
$this->_firstPageString = $firstPageString;
}
/**
* 设置上一页导航显示字符
* @param string $previousPageString: 上一页显示字符
*/
public function setPreviousPageString($previousPageString)
{
$this->_previousPageString = $previousPageString;
}
/**
* 设置下一页导航显示字符
* @param string $nextPageString:下一页显示字符
*/
public function setNextPageString($nextPageString)
{
$this->_nextPageString = $nextPageString;
}
/**
* 设置未页导航显示字符
* @param string $nextPageString:未页显示字符
*/
public function setLastPageString($lastPageString)
{
$this->_lastPageString = $lastPageString;
}
/**
* 设置导航字符显示位置
* @param string $align:导航位置
*/
public function setAlign($align)
{
$align = strtolower($align);
if($align == "center")
{
$this->_align = "center";
}elseif($align == "right")
{
$this->_align = "right";
}else
{
$this->_align = "left";
}
}
/**
* 设置页面参数名称
* @param string $pageParamName:页面参数名称
*/
public function setPageParamName($pageParamName)
{
$this->_PageParaName = $pageParamName;
}
/**
* 获取页面参数名称
* @return string 页面参数名称
*/
public function getPageParamName()
{
return $this->_PageParaName;
}
/**
* 生成导航链接地址
* @param int $targetPage:导航页
* @return string 链接目标地址
*/
private function createHref($targetPage = null)
{
$params = $this->_front->getRequest()->getParams();
$module = $params["module"];
$controller = $params["controller"];
$action = $params["action"];
//add by ma
if($this->_isUsingModule == 0)
$targetUrl = $this->_front->getBaseUrl()."/$controller/$action";
else
$targetUrl = $this->_front->getBaseUrl()."/$module/$controller/$action";
foreach ($params as $key => $value)
{
if($key != "controller" && $key != "module" && $key != "action" && $key != $this->_PageParaName)
{
$targetUrl .= "/$key/$value";
}
}
if(isset($targetPage)) // 指定目标页
$targetUrl .= "/$this->_PageParaName/$targetPage";
else
$targetUrl .= "/$this->_PageParaName/";
return $targetUrl;
}
}
?>
template code:
Code
<%
var databaseName = input.Item("cmbDatabase");
var tablenames = input.Item("lstTables");
var database = MyMeta.Databases.Item(databaseName);
// Filename info
var filepath = input.item("txtPath");
if (filepath.charAt(filepath.length - 1) != '\\') filepath += "\\";
tablePath = filepath + "DbTable\\";
// The buffer that will hold all the output for rendering.
//var buffer = "";
for (var i = 0; i < tablenames.Count; i++)
{
var tableName = tablenames.Item(i);
var tableMeta = database.Tables.Item(tableName);
//var objectAlias = tableMeta.Alias.split("_").join("");
var objectAlias = tableMeta.Alias;
var hasAutoKey = false;
// Build the filename
var modelFileName = filepath + objectAlias + ".php";
var tableFileName = tablePath + objectAlias + ".php";
%>
<?php
require_once 'Zend/Db/Table/Abstract.php';
/**
* DbTable <%= tableName %>
*/
class Model_DbTable_<%= objectAlias %> extends Zend_Db_Table_Abstract
{
protected $_name = "<%= tableName %>";
protected $_primary = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write(curKey.Name);}%>";
}
?>
<%
output.save(tableFileName, false);
output.clear();
%>
<?php
require_once APPLICATION_PATH . '/components/tc_Singleton.php';
/**
* <%= objectAlias %> model
*
*/
class Model_<%= objectAlias %>
{
/**
* save method
*/
public function save (array $data)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$filelds = $table->info(Zend_Db_Table_Abstract::COLS);
foreach ($data as $key => $value) {
if (! in_array($key, $filelds)) {
unset($data[$key]);
}
}
<%
if(tableMeta.PrimaryKeys.Count ==1){
var colPri = tableMeta.PrimaryKeys.Item(0);
if(colPri.IsAutoKey){
%>
unset($data['<%= tableMeta.PrimaryKeys.Item(0).Name %>']);
<% }} //end unset primary key%>
return $table->insert($data);
}
/**
* update <%= objectAlias %> info.
*/
public function update ($data, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$da = $table->getAdapter();
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
foreach ($data as $field => $value) {
if (! in_array($field, $fields)) {
unset($data[$field]);
}
}
<%
if(tableMeta.PrimaryKeys.Count ==1){
var colPri = tableMeta.PrimaryKeys.Item(0);
if(colPri.IsAutoKey){
%>
unset($data['<%= tableMeta.PrimaryKeys.Item(0).Name %>']);
<% }} //end unset primary key%>
$whereClause = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(" and "); output.write(curKey.Name+"=?");}%>";
return $table->update($data, $da->quoteInto($whereClause, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>));
}
/**
* get paged all
*/
public function get_paged_all($page_index=1,$page_num = 20,$where='',$order='')
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$selector = $table->select();
if(strlen($where)>0)
$selector->where($where);
if(strlen($order)>0)
$selector->order($order);
$selector->limit($page_num,($page_index -1)*$page_num);
return $table->fetchAll($selector)->toArray();
}
/**
* delete by primary
*/
public function delete (<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$da = $table->getAdapter();
$whereClause = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(" and "); output.write(curKey.Name+"=?");}%>";
$table->delete($da->quoteInto($whereClause, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>));
}
/**
* get count
*/
public function get_count($condition=null)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$ad = $table ->getAdapter();
if(isset($condition))
return $ad->fetchOne('select count(*) from <%= tableName %> where '.$condition);
else
return $ad->fetchOne('select count(*) from <%= tableName %>');
}
<%
var indexs = tableMeta.Indexes;
//output all find by index method.
for(var k=0;k < indexs.Count;k++)
{
var curIndex = indexs.Item(k);
if(curIndex.Name != "PRIMARY")
{
%>
/**
* get by IX_<%= curIndex.Name %>
*/
public function find_IX_<%= curIndex.Name %>(<% for(var m=0;m<curIndex.Columns.Count;m++) {var curCol = curIndex.Columns.Item(m);if(curCol.HasDefault) output.write("$" + curCol.Name+"="+curCol.Default+","); else output.write("$"+curCol.Name + ",");} %>$page_index=1,$page_num = 20,$where='',$order='')
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$selector = $table->select();
<%
for(var m=0;m<curIndex.Columns.Count;m++)
{
var curCol = curIndex.Columns.Item(m);
output.writeln("$selector->where($da->quoteInto('"+curCol.Name+"=?',$"+curCol.Name+"));");
}
%>
if(strlen($where)>0)
$selector->where($where);
if(strlen($order)>0)
$selector->order($order);
$selector->limit($page_num,($page_index -1)*$page_num);
return $table->fetchAll($selector)->toArray();
}
<%
}
else
{
%>
/**
* find by primary
*/
public function find (<% for(var m=0;m<curIndex.Columns.Count;m++) {var curCol = curIndex.Columns.Item(m);if(m>0){output.write(",");} if(curCol.HasDefault) output.write("$" + curCol.Name+"="+curCol.Default); else output.write("$"+curCol.Name);} %>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$ad = $table->getAdapter();
$selector = $table->select();
<%
for(var m=0;m<curIndex.Columns.Count;m++)
{
var curCol = curIndex.Columns.Item(m);
output.writeln("$selector->where($da->quoteInto('"+curCol.Name+"=?',$"+curCol.Name+"));");
}
%>
return $table->fetchRow($selector);
}
<%
}
}
%>
}
?>
<%
// Save this set of procedures to disk
output.save(modelFileName, false);
//buffer = output.text;
output.clear();
}
output.write("生成成功!");//output the text to console window.
%>
<%
var databaseName = input.Item("cmbDatabase");
var tablenames = input.Item("lstTables");
var database = MyMeta.Databases.Item(databaseName);
// Filename info
var filepath = input.item("txtPath");
if (filepath.charAt(filepath.length - 1) != '\\') filepath += "\\";
tablePath = filepath + "DbTable\\";
// The buffer that will hold all the output for rendering.
//var buffer = "";
for (var i = 0; i < tablenames.Count; i++)
{
var tableName = tablenames.Item(i);
var tableMeta = database.Tables.Item(tableName);
//var objectAlias = tableMeta.Alias.split("_").join("");
var objectAlias = tableMeta.Alias;
var hasAutoKey = false;
// Build the filename
var modelFileName = filepath + objectAlias + ".php";
var tableFileName = tablePath + objectAlias + ".php";
%>
<?php
require_once 'Zend/Db/Table/Abstract.php';
/**
* DbTable <%= tableName %>
*/
class Model_DbTable_<%= objectAlias %> extends Zend_Db_Table_Abstract
{
protected $_name = "<%= tableName %>";
protected $_primary = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write(curKey.Name);}%>";
}
?>
<%
output.save(tableFileName, false);
output.clear();
%>
<?php
require_once APPLICATION_PATH . '/components/tc_Singleton.php';
/**
* <%= objectAlias %> model
*
*/
class Model_<%= objectAlias %>
{
/**
* save method
*/
public function save (array $data)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$filelds = $table->info(Zend_Db_Table_Abstract::COLS);
foreach ($data as $key => $value) {
if (! in_array($key, $filelds)) {
unset($data[$key]);
}
}
<%
if(tableMeta.PrimaryKeys.Count ==1){
var colPri = tableMeta.PrimaryKeys.Item(0);
if(colPri.IsAutoKey){
%>
unset($data['<%= tableMeta.PrimaryKeys.Item(0).Name %>']);
<% }} //end unset primary key%>
return $table->insert($data);
}
/**
* update <%= objectAlias %> info.
*/
public function update ($data, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$da = $table->getAdapter();
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
foreach ($data as $field => $value) {
if (! in_array($field, $fields)) {
unset($data[$field]);
}
}
<%
if(tableMeta.PrimaryKeys.Count ==1){
var colPri = tableMeta.PrimaryKeys.Item(0);
if(colPri.IsAutoKey){
%>
unset($data['<%= tableMeta.PrimaryKeys.Item(0).Name %>']);
<% }} //end unset primary key%>
$whereClause = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(" and "); output.write(curKey.Name+"=?");}%>";
return $table->update($data, $da->quoteInto($whereClause, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>));
}
/**
* get paged all
*/
public function get_paged_all($page_index=1,$page_num = 20,$where='',$order='')
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$selector = $table->select();
if(strlen($where)>0)
$selector->where($where);
if(strlen($order)>0)
$selector->order($order);
$selector->limit($page_num,($page_index -1)*$page_num);
return $table->fetchAll($selector)->toArray();
}
/**
* delete by primary
*/
public function delete (<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$da = $table->getAdapter();
$whereClause = "<% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(" and "); output.write(curKey.Name+"=?");}%>";
$table->delete($da->quoteInto($whereClause, <% for(var mm=0;mm<tableMeta.PrimaryKeys.Count;mm++){var curKey=tableMeta.PrimaryKeys.Item(mm);if(mm>0) output.write(","); output.write("$"+curKey.Name);}%>));
}
/**
* get count
*/
public function get_count($condition=null)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$ad = $table ->getAdapter();
if(isset($condition))
return $ad->fetchOne('select count(*) from <%= tableName %> where '.$condition);
else
return $ad->fetchOne('select count(*) from <%= tableName %>');
}
<%
var indexs = tableMeta.Indexes;
//output all find by index method.
for(var k=0;k < indexs.Count;k++)
{
var curIndex = indexs.Item(k);
if(curIndex.Name != "PRIMARY")
{
%>
/**
* get by IX_<%= curIndex.Name %>
*/
public function find_IX_<%= curIndex.Name %>(<% for(var m=0;m<curIndex.Columns.Count;m++) {var curCol = curIndex.Columns.Item(m);if(curCol.HasDefault) output.write("$" + curCol.Name+"="+curCol.Default+","); else output.write("$"+curCol.Name + ",");} %>$page_index=1,$page_num = 20,$where='',$order='')
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$selector = $table->select();
<%
for(var m=0;m<curIndex.Columns.Count;m++)
{
var curCol = curIndex.Columns.Item(m);
output.writeln("$selector->where($da->quoteInto('"+curCol.Name+"=?',$"+curCol.Name+"));");
}
%>
if(strlen($where)>0)
$selector->where($where);
if(strlen($order)>0)
$selector->order($order);
$selector->limit($page_num,($page_index -1)*$page_num);
return $table->fetchAll($selector)->toArray();
}
<%
}
else
{
%>
/**
* find by primary
*/
public function find (<% for(var m=0;m<curIndex.Columns.Count;m++) {var curCol = curIndex.Columns.Item(m);if(m>0){output.write(",");} if(curCol.HasDefault) output.write("$" + curCol.Name+"="+curCol.Default); else output.write("$"+curCol.Name);} %>)
{
$table = tc_Singleton::getInstance('t_<%= objectAlias %>');
$ad = $table->getAdapter();
$selector = $table->select();
<%
for(var m=0;m<curIndex.Columns.Count;m++)
{
var curCol = curIndex.Columns.Item(m);
output.writeln("$selector->where($da->quoteInto('"+curCol.Name+"=?',$"+curCol.Name+"));");
}
%>
return $table->fetchRow($selector);
}
<%
}
}
%>
}
?>
<%
// Save this set of procedures to disk
output.save(modelFileName, false);
//buffer = output.text;
output.clear();
}
output.write("生成成功!");//output the text to console window.
%>
interface code
Code
function setup()
{
ui.Title = "Generate PHP Zend Framework components by Darkangle QQ5364241";
ui.Width = 350;
ui.Height = 430;
// Grab default output path
var sOutputPath = "";
if (input.Contains("defaultOutputPath"))
{
sOutputPath = input.Item("defaultOutputPath");
}
// Display and errors here
var lblError = ui.AddLabel("lblError", "", "");
lblError.ForeColor = "Red";
// Setup Folder selection input control.
var lblPath = ui.AddLabel("lblPath", "Select the output path:", "Select the output path in the field below.");
var outpath = ui.AddTextBox("txtPath", sOutputPath, "Select the Output Path.");
var btnSelectPath = ui.AddFilePicker("btnPath", "Select Path", "Select the Output Path.", "txtPath", true);
// Setup Database selection combobox.
var label_d = ui.AddLabel("lblDatabases", "Select a database:", "Select a database in the dropdown below.");
var cmbDatabases = ui.AddComboBox("cmbDatabase", "Select a database.");
// Setup Tables selection multi-select listbox.
var label_t = ui.AddLabel("lblTables", "Select tables:", "Select tables from the listbox below.");
var lstTables = ui.AddListBox("lstTables", "Select tables.");
lstTables.Height = 150;
// Attach the onchange event to the cmbDatabases control.
setupDatabaseDropdown(cmbDatabases, lblError);
cmbDatabases.AttachEvent("onchange", "cmbDatabases_onchange");
ui.ShowGUI = true;
}
function setupDatabaseDropdown(cmbDatabases, lblError)
{
try
{
if (MyMeta.IsConnected)
{
cmbDatabases.BindData(MyMeta.Databases);
if (MyMeta.DefaultDatabase != null)
{
cmbDatabases.SelectedValue = MyMeta.DefaultDatabase.Name;
bindTables(cmbDatabases.SelectedValue);
}
lblError.Text = "";
}
else
{
lblError.Text = "Please set up your database connection in the Default Settings dialog.";
}
}
catch (error)
{
lblError.Text = "" + error + ", " + error.number + ", " + error.description;
}
}
function bindTables(sDatabase)
{
var lblError = ui.item("lblError");
var count = 0
var lstTables = ui.item("lstTables");
try
{
var db = MyMeta.Databases.Item(sDatabase);
lstTables.BindData(db.Tables);
lblError.Text = "";
}
catch (error)
{
lblError.Text = "" + error + ", " + error.number + ", " + error.description;
}
}
function cmbDatabases_onchange(control)
{
var lblError = ui.item("lblError");
var count = 0
var cmbDatabases = ui.item("cmbDatabase");
bindTables(cmbDatabases.SelectedText);
}
function setup()
{
ui.Title = "Generate PHP Zend Framework components by Darkangle QQ5364241";
ui.Width = 350;
ui.Height = 430;
// Grab default output path
var sOutputPath = "";
if (input.Contains("defaultOutputPath"))
{
sOutputPath = input.Item("defaultOutputPath");
}
// Display and errors here
var lblError = ui.AddLabel("lblError", "", "");
lblError.ForeColor = "Red";
// Setup Folder selection input control.
var lblPath = ui.AddLabel("lblPath", "Select the output path:", "Select the output path in the field below.");
var outpath = ui.AddTextBox("txtPath", sOutputPath, "Select the Output Path.");
var btnSelectPath = ui.AddFilePicker("btnPath", "Select Path", "Select the Output Path.", "txtPath", true);
// Setup Database selection combobox.
var label_d = ui.AddLabel("lblDatabases", "Select a database:", "Select a database in the dropdown below.");
var cmbDatabases = ui.AddComboBox("cmbDatabase", "Select a database.");
// Setup Tables selection multi-select listbox.
var label_t = ui.AddLabel("lblTables", "Select tables:", "Select tables from the listbox below.");
var lstTables = ui.AddListBox("lstTables", "Select tables.");
lstTables.Height = 150;
// Attach the onchange event to the cmbDatabases control.
setupDatabaseDropdown(cmbDatabases, lblError);
cmbDatabases.AttachEvent("onchange", "cmbDatabases_onchange");
ui.ShowGUI = true;
}
function setupDatabaseDropdown(cmbDatabases, lblError)
{
try
{
if (MyMeta.IsConnected)
{
cmbDatabases.BindData(MyMeta.Databases);
if (MyMeta.DefaultDatabase != null)
{
cmbDatabases.SelectedValue = MyMeta.DefaultDatabase.Name;
bindTables(cmbDatabases.SelectedValue);
}
lblError.Text = "";
}
else
{
lblError.Text = "Please set up your database connection in the Default Settings dialog.";
}
}
catch (error)
{
lblError.Text = "" + error + ", " + error.number + ", " + error.description;
}
}
function bindTables(sDatabase)
{
var lblError = ui.item("lblError");
var count = 0
var lstTables = ui.item("lstTables");
try
{
var db = MyMeta.Databases.Item(sDatabase);
lstTables.BindData(db.Tables);
lblError.Text = "";
}
catch (error)
{
lblError.Text = "" + error + ", " + error.number + ", " + error.description;
}
}
function cmbDatabases_onchange(control)
{
var lblError = ui.item("lblError");
var count = 0
var cmbDatabases = ui.item("cmbDatabase");
bindTables(cmbDatabases.SelectedText);
}