ZendFramework快速入门

来源:互联网 发布:2014淘宝双11成交额 编辑:程序博客网 时间:2024/06/04 19:52
该教程来自Rob Allen的《Getting Started with Zend Framework》http://akrabat.com/zend-framework-tutorial/。该教程也有ZF2的版本:http://akrabat.com/getting-started-with-zend-framework-2/。这个DEMO演示了在Zend Framework框架下开发流程,对数据库的CRUD操作。更多内容可参看他的书《Zend Framework in Action》,Manning出版。

1 安装软件:
1.1 安装Zend Studio 8.0.1 ;zendstudio.net/3727234F6095F72034F6095F
1.2 安装ZendServer-CE-php-5.3.9-5.6.0-Windows_x86
安装MySQL和phpmyadmin,MySQL默认root密码为空;

2 配置ZendServer
2.1 修改Zend/ZendServer/etc/ZendEnablerConf.xml,把打头的乱码改成<?,重启apache。
2.2 登录ZendServer,http://localhost:10081/ZendServer/Login,可查看ZendServer配置,也可在此登录phpMyadmin。

3 创建ZendFramework项目及配置站点
3.1 打开ZendStudio,File>New>Zend Framework Project。
Project name:ZFHelloWorld
Create project on local server :D:\Program Files\Zend\Apache2\htdocs\ZFHelloWorld
Framework Version :1.11
Project Layout: Zend Framework default project structure
3.2 修改apache配置文件Zend/Apache2/conf/zend.conf
添加:<VirtualHost *:80>
    ServerName ZFHelloWorld
    DocumentRoot "D:/Program Files/Zend/Apache2/htdocs/ZFHelloWorld/public"
    SetEnv APPLICATION_ENV "development"
    <Directory "D:/Program Files/Zend/Apache2/htdocs/ZFHelloWorld/public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
重启apache。
3.3 修改host文件:C:\Windows\System32\drivers\etc\
添加:127.0.0.1 ZFHelloWorld
3.4 在浏览器打开:http://zfhelloworld/,可看到“Welcome to the Zend Framework!”界面。配置成功!

4 创建控制器
(几个需要了解的文件有:/application/configs/application.ini,/public/index.php,默认是创建了两个控制器ErrorController.php,IndexController.php,其相应的view(/application/views/scripts/index和error文件夹)关于ZF的文件夹结构在此略过,本文主要是记操作流程。
借助ZF Tool可以很方便的按ZF的要求生成文件,比如按ZF要求的命名规则来生成类名及文件名(ZF里可是要按约定来生成相关类的)。ZF Tool从ZendStudio的Project菜单下打开(要先选中一个ZF的项目),关闭ZF Tool的方法是单击ZFTool左上角的绿色图标即可。)
4.1 给IndexController添加action
ZFTool:
zf create action add Index
4.2
zf create action edit Index
4.3
zf create action delete Index
(执行命令之后,IndexController.php为多了三个方法add,edit,delete,同时在view/script/index下多了三个视图:delete.phtml,edit.phtml,index.phtml)

5 创建数据库及配置
5.1 在phpmyadmin(http://localhost:10081/phpMyAdmin/)中创建数据库:ZFHelloWorld,
5.2 创建表:
CREATE TABLE albums (
id int(11) NOT NULL auto_increment,
artist varchar(100) NOT NULL,
title varchar(100) NOT NULL,
PRIMARY KEY (id)
);
5.3 插入测试数据:
INSERT INTO albums (artist, title)
VALUES
('Paolo Nutine', 'Sunny Side Up'),
('Florence + The Machine', 'Lungs'),
('Massive Attack', 'Heligoland'),
('Andre Rieu', 'Forever Vienna'),
('Sade', 'Soldier of Love');
5.4 配置数据库连接信息(application/configs/application.ini),在[production]节添加:
resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = ZFHelloWorld

6 创建Model
6.1 ZF Tool:zf create db-table Albums albums。
(会生成/application/models/DbTable/Albums.php,Albums.php中类名为Application_Model_DbTable_Albums,继承自Zend_Db_Table_Abstract。
其中的成员$_name代表了数据库中对应的表格名称。)

7 设置布局
7.1 ZFTool:zf enable layout
(会生成/application/layouts/scripts/layout.phtml,并在application.ini中自动添加配置项resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/")
7.2 修改/application/layouts/scripts/layout.phtml:
<?php
  $this->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
  $this->headTitle()->setSeparator(' - ');
  $this->headTitle('Zend Framework Tutorial');
  echo $this->doctype(); ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <?php echo $this->headMeta(); ?>
  <?php echo $this->headTitle(); ?>
</head>
<body>
<div id="content">
<h1><?php echo $this->escape($this->title); ?></h1>
<?php echo $this->layout()->content; ?>
</div>
</body>
</html>
7.3 设置视图文档类型
在application.ini的[production]节添加:
resources.view.doctype = "XHTML1_STRICT"
7.4 添加样式
新建文件及文件夹 /Public/css/site.css,site.css内容:
body,html {
margin: 0 5px;
font-family: Verdana,sans-serif;
}
h1 {
font-size: 1.4em;
color: #008000;
}
a {
color: #008000;
}

th {
text-align: left;
}
td, th {padding-right: 5px;
}

form dt {
width: 100px;
display: block;
float: left;
clear: left;
}
form dd {
margin-left: 0;
float: left;
}
form #submitbutton {
margin-left: 100px;
}
7.5 给/application/layouts/scripts/layout.phtml添加样式引用:
...
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
<?php echo $this->headLink()->prependStylesheet($this->baseUrl().'/css/site.css'); ?>
</head>
...

8 显示所有记录
8.1 Controller:
application/controllers/IndexController.php,修改
function indexAction()
{
  $albums = new Application_Model_DbTable_Albums();
  $this->view->albums = $albums->fetchAll();
}

8.2 View:
zf-tutorial/application/views/scripts/index/index.phtml
<?php
  $this->title = "My Albums";
  $this->headTitle($this->title);
?>
<p><a href="<?php echo $this->url(array('controller'=>'index','action'=>'add'));?>">Add new album</a></p>
<table>
<tr>
  <th>Title</th>
  <th>Artist</th>
  <th>&nbsp;</th>
</tr>
<?php foreach($this->albums as $album) : ?>
<tr>
<td><?php echo $this->escape($album->title);?></td>
<td><?php echo $this->escape($album->artist);?></td>
<td>
<a href="<?php echo $this->url(array('controller'=>'index','action'=>'edit', 'id'=>$album->id));?>">Edit</a>
<a href="<?php echo $this->url(array('controller'=>'index','action'=>'delete', 'id'=>$album->id));?>">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
8.3 http://zfhelloworld即可看到所有记录的列表。

9 插入新记录
9.1 Model:/application/models/DbTable/Albums.php
    public function addAlbum ($artist, $title)
    {
        $data = array('artist' => $artist, 'title' => $title);
        $this->insert($data);
    }

9.2 Form:
ZF Tool:zf create form Album
/application/forms/Album.php
public function init ()
        {
            $this->setName('album');
            $id = new Zend_Form_Element_Hidden('id');
            $id->addFilter('Int');
            $artist = new Zend_Form_Element_Text('artist');
            $artist->setLabel('Artist')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
            $title = new Zend_Form_Element_Text('title');
            $title->setLabel('Title')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
            $submit = new Zend_Form_Element_Submit('submit');
            $submit->setAttrib('id', 'submitbutton');
            $this->addElements(array($id, $artist, $title, $submit));
        }
9.3 Controller:application/controllers/IndexController.php的addAction
$form = new Application_Form_Album();
$form->submit->setLabel('Add');
$this->view->form = $form;
9.4 View:application/views/scripts/index/add.phtml
<?php
    $this->title = "Add new album";
    $this->headTitle($this->title);
    echo $this->form ;
?>
9.5 此时已可以看到添加的界面,但addaction还未有处理提交之后的功能,继续修改application/controllers/IndexController.php的addAction
    public function addAction()
    {
        // action body
        $form = new Application_Form_Album();
        $form->submit->setLabel('Add');
        $this->view->form = $form;
       
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $artist = $form->getValue('artist');
                $title = $form->getValue('title');
                $albums = new Application_Model_DbTable_Albums();
                $albums->addAlbum($artist, $title);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }
到此,添加功能完成。

10 编辑指定行
10.1 model:/application/models/DbTable/Albums.php
    public function getAlbum ($id)
    {
        $id = (int) $id;
        $row = $this->fetchRow('id = ' . $id);
        if (!$row) {
            throw new Exception("Could not find row $id");
        }
        return $row->toArray();
    }
10.2 Controller:application/controllers/IndexController.php的editAction
        $form = new Application_Form_Album();
        $form->submit->setLabel('Save');
        $this->view->form = $form;
        $id = $this->_getParam('id', 0);
        if ($id > 0) {
            $albums = new Application_Model_DbTable_Albums();
            $form->populate($albums->getAlbum($id));
        }
10.3 View:applicaton/views/scripts/index/edit.phtml
<?php
$this->title = "Edit album";
$this->headTitle($this->title);
echo $this->form ;
?>
此时点击edit链接可进入指定记录的编辑页面,但保存功能尚未实现。下面将实现编辑保存功能
10.4 Model:
/application/models/DbTable/Albums.php
添加
    public function updateAlbum ($id, $artist, $title)
    {
        $data = array('artist' => $artist, 'title' => $title);
        $this->update($data,'id = '.(int)$id);
    }
10.5 Controller:
修改application/controllers/IndexController.php的editAction
$form = new Application_Form_Album();
            $form->submit->setLabel('Save');
            $this->view->form = $form;
            //添加post处理
            if ($this->getRequest()->isPost()) {
                $formData = $this->getRequest()->getPost();
                if ($form->isValid($formData)) {
                    $id = (int) $form->getValue('id');
                    $artist = $form->getValue('artist');
                    $title = $form->getValue('title');
                    $albums = new Application_Model_DbTable_Albums();
                    $albums->updateAlbum($id, $artist, $title);
                    $this->_helper->redirector('index');
                } else {
                    $form->populate($formData);
                }
            } else {
                $id = $this->_getParam('id', 0);
                if ($id > 0) {
                    $albums = new Application_Model_DbTable_Albums();
                    $form->populate($albums->getAlbum($id));
                }
            }
到此编辑界面的保存功能有效。

11 删除操作:
11.1 Model:/application/models/DbTable/Albums.php
public function deleteAlbum($id)
{
   $this->delete('id =' . (int)$id);
}
11.2 Controller:修改application/controllers/IndexController.php的deleteAction
   public function deleteAction()
    {
        if ($this->getRequest()->isPost()) {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Yes') {
                $id = $this->getRequest()->getPost('id');
                $albums = new Application_Model_DbTable_Albums();
                $albums->deleteAlbum($id);
            }
            $this->_helper->redirector('index');
        } else {
            $id = $this->_getParam('id', 0);
            $albums = new Application_Model_DbTable_Albums();
            $this->view->album = $albums->getAlbum($id);
        }
    }
11.3 View:application/views/scripts/delete.phtml
<?php
$this->title = "Delete album";
$this->headTitle($this->title);
?>
<p>Are you sure that you want to delete
'<?php echo $this->escape($this->album['title']); ?>' by
'<?php echo $this->escape($this->album['artist']); ?>'?
</p>
<form action="<?php echo $this->url(array('action'=>'delete')); ?>" method="post">
<div>
<input type="hidden" name="id" value="<?php echo $this->album['id']; ?>" />
<input type="submit" name="del" value="Yes" />
<input type="submit" name="del" value="No" />
</div>
</form>
到此删除功能实现。

end.......................>>>>>>>>>>>>>>>>>>>>>>>>>>
原创粉丝点击