進入public文件夾,修改入口文件index.php
創建項目時,入口文件的內容已經寫好了,不過為了讓models的類能自動加載,做一些改動
// Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), realpath(APPLICATION_PATH . '/'), get_include_path(),)));//找到上面內容,加入 realpath(APPLICATION_PATH . '/models'),
當然也可以把models放到library文件夾下,就不用做這一步了
進入項目到application\configs修改application.ini
在[production]下添加數據庫配置
;=========== 數據庫配置 resources.db.adapter = PDO_MYSQL resources.db.params.host = localhost resources.db.params.username = root resources.db.params.password = root resources.db.params.dbname = cms resources.db.params.charset = utf8 resources.db.isDefaultTableAdapter = true resources.db.params.driver_options.1002 = "SET NAMES UTF8;"
接下來再添加類自動加載的前綴,用於之後在調用類時自動加載,不用再一個一個寫include了
;=========== 類自動加載的前綴 autoloadernamespaces.0 = "models_";如果還需要再添加其他前綴,如m2_,m3_,就在接下加上 autoloadernamespaces.1 = "m2_" autoloadernamespaces.2 = "m3_"
以此類推
application.ini就初步修改完了
進行測試
在數據庫加個測試的表class,字段有id,name,parentId
在models下創建類class.php
class models_class extends Zend_Db_Table{ protected $_name ="class"; protected $_primary = 'id'; public $_db; public function init(){ $this->_db = $this->getAdapter(); }}
注意,zf的類名命名規則是 文件夾名+下劃線+類名,如
models/class.php 要命名為 models_class
models/aaa/testclass.php 要命名 models_aaa_testclass
進入application\controllers\IndexController.php,讀取class的數據,在indexAction()添加
$class=new models_class(); $this->view->class_str = $class->fetchAll()->toArray();
進入application\views\scripts\index修改index.phtml,添加
<div style=”width:600px;”><?php var_dump($this->class_str); ?></div>
刷新頁面,可以看到顯示數據
controller下對數據庫的操作方法備忘
//獲得db $bootstrap = $this->getFrontController()->getParam('bootstrap'); $bootstrap->bootstrap('db'); $db = $bootstrap->getResource('db');
//插入數據 $data = array('name' => '測試項' ,'parentId' => '0'); $ret = $db->insert('class',$data);if($ret){ $getId = $db->lastInsertId();}
//更新數據 $data = array ('parentId' => '1'); $where = $db->quoteInto('`id` = ?','13'); $rs = $db->update('class', $data, $where);
//查找數據 $select = $db->select(); $select->from('class', '*'); $select->where('`id` <= ?','5');//$select->where('id IN(?)', array(1, 2, 3)); $sql = $select->__toString(); $result = $db->fetchAll($sql);
在類中對數據庫的操作也很類似,下面在類中寫個getClass的函數,功能和前面的$class->fetchAll()->toArray()一樣
class models_class extends Zend_Db_Table{ protected $_name ="class"; protected $_primary = 'id'; public $_db; public function init(){ $this->_db = $this->getAdapter(); } public function getClass(){ $select = $this->_db->select(); $select->from($this->_name, '*'); $sql = $select->__toString(); $result = $this->_db->fetchAll($sql); return $result; }}