启动顺序
publicindex.php 入口总控初始化 $application->bootstrap()->run()
applicationBootstrap.php 所有控制器入口
IndexController.php 单控制器初始化init()
indexController.php 调用函数 indexAction()
在applicationconfigsapplication.ini添加数据库配置
[mysql] db.adapter = PDO_MYSQL db.params.host = localhost db.params.username = root db.params.password = 123 db.params.dbname = test
在applicationBootstrap.php做初始化数据库适配器
<?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { function __construct($app){ parent::__construct($app); //初始化数据库适配器 $url = constant("APPLICATION_PATH").DIRECTORY_SEPARATOR.'configsapplication.ini'; $dbconfig = new Zend_Config_Ini($url, 'mysql'); $db = Zend_Db::factory($dbconfig->db); $db->query('SET NAMES UTF8'); Zend_Db_Table::setDefaultAdapter($db); } }
也可在applicationcontrollersIndexController.php的init()函数中添加。
在applicationmodels目录下建立模型
<?php //数据库user表的操作模型 class UserModel extends Zend_Db_Table{ protected $_name = 'user'; protected $_primary = 'id'; }
在applicationcontrollersIndexController.php中调用数据库接口查询和view显示
<?php require_once APPLICATION_PATH . '/models/userModel.php'; class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { // action body $user = new UserModel(); $arr = $user->fetchAll()->toArray(); //print_r($res); //把数据传递给view (obj/array/int...) $this->view->rows = $arr; //默认调用index模板 $this->render('index'); } }
最后在applicationviewsindexindex.phtml中显示数据
<?php foreach ($this->rows as $r){?> <ul><li><?php echo $r['id'];?></li> <li><?php echo $r['FirstName'];?></li> <li><?php echo $r['LastName'];?></li> <li><?php echo $r['Age'];?></li> <li><?php echo $r['Job'];?></li> <li><?php echo $r['Hometown'];?></li></ul> <?php }?>