MVC架构与控制器视图交互
在Zend Framework中进行MVC代码编写时,首先需关注控制器的结构。
以下是具体的代码示例:
} function indexAction() { $this->view->word=" I love spurs";
echo $this->view->render("index.html");} function addAction(){ //如果是POST过来的值.就增加.否则就显示增加页面
}
}
?>
在控制器内部编写业务逻辑内容:
复制代码 代码如下: $this->view->word="ggg"; $this->view->render("index.html"); ---->index.html echo $this->word;
数据库配置文件加载与连接
配置文件位于 application->config.ini [general] db.adapter=PDO_MYSQL db.config.host=localhost db.config.username=root db.config.password= db.config.dbname=think_zw
需要将上述配置文件引入到framework框架中。
复制代码 代码如下: //配置数据库参数,并连接数据库 $config=new Zend_Config_Ini('./application/config/config.ini',null, true); Zend_Registry::set('config',$config); $dbAdapter=Zend_Db::factory($config->general->db->adapter,$config->general->db->config->toArray()); $dbAdapter->query('SET NAMES UTF8'); Zend_Db_Table::setDefaultAdapter($dbAdapter); Zend_Registry::set('dbAdapter',$dbAdapter);
单一入口路由与模块实例化
采用单一入口模式:localhost/index/add/用于访问index模块下的add方法。 function addAction(){}(在IndexController.php) 默认访问为index模块下的index方法
接着在model目录中建立一个模块message.php。
复制代码 代码如下:
进行模块实例化操作:
复制代码 代码如下: function indexAction() { $message=new message();//实例化数据库类
//获取数据库内容
$this->view->messages=$message->fetchAll()->toArray();
echo $this->view->render('index.phtml');//显示模版
}<?foreach ($this->messages as $message): ?>
<?php echo $message['title']; ?><?php echo $message['content']; ?><?endforeach ; ?>
数据修改删除与异常处理
************* 修改和删除数据
复制代码 代码如下: kk ll
在index.phtml模板文件中添加相关代码:
复制代码 代码如下: baseUrl?>/index/exit">编辑 baseUrl?>/index/delete">删除
添加一个新的方法:edit.phtml
复制代码 代码如下: function editAction(){
$message = new Message();
$db = $message->getAdapter();
if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){
$id = $this->_request->getPost('id');
$cid = $this->_request->getPost('cid');
$title = $this->_request->getPost('title');
$set = array(
'cid'=>$cid,
'title'=>$title
);
$where = $db->quoteInto('id = ?',$id);
//更新数据
$message->update($set,$where);
unset($set);
echo '修改数据成功!view->baseUrl.'/index/index/">返回';
}else{
$id = $this->_request->getParam('id');
$this->view->messages = $message->fetchAll('id='.$id)->toArray();
echo $this->view->render('edit.phtml');
}
}
function delAction(){
$message = new Message();
$id = (int)$this->_request->getParam('id');
if($id > 0){
$where = 'id = ' . $id;
$message->delete($where);
}
echo '删除数据成功!view->baseUrl.'/index/index/">返回';
}开发过程中可能出现的异常:
复制代码 代码如下: Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (index.php)' in
解决办法:在index.php中的
复制代码 代码如下: $frontController =Zend_Controller_Front::getInstance();后加上 $frontController->setParam('useDefaultControllerAlways', true);
******* id/3 等于以前的?id=3