对于简单的应用程序并在 ZF 中涉足,只需使用将数据库表绑定到数据库适配器的 DbTable 模型即可开始。这不是最佳实践,但它很容易,可以帮助您入门。
使用 Zend_Tool cli 命令将具有这种格式
zf create db-table name actual-table-name module force-overwrite
,
它将转换为:
zf create db-table Users users
db 这将创建一个名为Users.php
at的文件/application/models/DbTable/
,它看起来像:
<?php
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
protected $_name = 'users'; //name of table, does not have to match name of class
}
现在在控制器中使用它fetchAll
很简单:
<?php
class IndexController extends Zend_Controller_Action {
public function indexAction(){
$db = new Application_Model_DbTable_Users();//instantiate model
$result = $db->fetchAll();//perform query, see Zend_Db_Table_Abstract for API
$this->view->users = $result;//send to view
}
}
只需制作这个小类,您就可以访问所选数据库适配器的功能。您还可以在 DbTable 模型中构建方法来自定义您的访问需求。
<?php
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
protected $_name = 'users'; //name of table, does not have to match name of class
public function getUser($id) {
$select = $this->select();//see Zend_Db_Select for info, provides more secure interface for building queries.
$select->where('id = ?', $id);//can be chained
$result = $this->fetchRow($select);//returns a row object, if array is needed use ->toArray()
return $result;
}
}
此方法的使用方式与 fetchAll() 方法类似:
<?php
class IndexController extends Zend_Controller_Action {
public function indexAction(){
$id = $this->getRequest()->getParam('id');//assumes the id is set somehow and posted
$db = new Application_Model_DbTable_Users();//instantiate model
$result = $db->getUser($id);//perform query, see Zend_Db_Table_Abstract for API
//$this->view->user = $result;//send to view as object
$this->view->user = $result->toArray();//send to view as an array
}
}
希望这可以帮助您入门,不要忘记阅读手册