Zend Framework(二) model与view使用

来源:互联网 发布:java 去除 转义字符 编辑:程序博客网 时间:2024/05/21 07:09

1、配置文件配置数据库选项,application/configs/application.ini中添加

[mysql]
db.adapter = PDO_MYSQL                          
db.params.host = localhost                  #数据库服务器名称
db.params.username = root                 #数据库用户名
db.params.password = ****                  #数据库密码
db.params.dbname = news                    #数据库名字


2、在application/Bootstrap.php中添加构造函数

   function __construct($app){
     
      parent::__construct($app);
      //初始化数据库适配器
      $url = constant("APPLICATION_PATH").DIRECTORY_SEPARATOR.'/configs/application.ini';
         
        $dbconfig = new Zend_Config_Ini($url , "mysql");
 
        $db = Zend_Db::factory( $dbconfig->db);
         
        $db->query('set names utf8');
         
        Zend_Db_Table::setDefaultAdapter($db);
         

      }

3、在application/models下建立model文件

如:User.php

<?php
class User extends Zend_Db_Table{
protected $_name='user';       //数据表名

protected $_parimary='uid';   //数据表主键


}

4、在application/controllers/IndexController.php(控制器任意)写代码,

如:

require_once APPLICATION_PATH.'/models/User.php';  //引入model文件
class IndexController extends Zend_Controller_Action
{


    public function init()
    {
   
        /* Initialize action controller here */
    }


    public function indexAction()
    {
        // action body
        $m = new User();  //实例化model
        $res = $m->fetchAll()->toArray();             //全表查询并转换成数组数据
        $this->view->res = $res;   //传送数据到index.phtml 模板
        
    }




}

5、在views/scripts/index/index.phtml中使用原生php输出数据,如

<?php
 foreach ($this->res as  $v) {
     # code...
    echo "uid: ".$v['uid']."----username:  ".$v['username']."<br/>";
 }
?>

6、再访问http://www.hunhun.com/index/index,则会看到数据表user表的数据输出

0 0