您的位置:首页 > 编程语言 > PHP开发

ZF一个新闻系统的例子

2008-10-24 14:06 232 查看
作者:Chris Shiflett
翻译:ShiningRay
我们邀请了PHP安全专家——兼最新发布的Zend Framework的贡献者——Chris Shiflett来为我们写一篇关于ZF主要特点的文章。
这份完整的、按部就班的教程通过向你展示如何应用框架写出一个简单的新闻管理系统,为你提供了构建实际应用的独特视角。
Zend Framework终于掀开了其神秘的面纱!尽管它尚处于开发过程的早期阶段,但本文将现在所能用的中最好的部分特别呈现给读者,并通过构建一个简单的应用这个过程引导你了解这个框架。
Zend很早就发布了框架并引入社区运作。写本指南只能针对框架今天的情况来列出其特点。因为本指南是在线发布的,所以我会在框架发生变化的时候及时更新本文,这样就能尽可能保持一致。

要求

Zend Framework 要求使用 PHP 5。为了能完全利用本指南中展示的代码,你还需要Apache Web服务器,因为范例应用(一个新闻管理系统)用到了mod_rewrite。
本指南中的代码可以自由下载,所以你可以亲自尝试一下。可以从Brain Bulb的网站上下载到:http://brainbulb.com/zend-framework-tutorial.tar.gz.

下载框架

在开始阅读本指南之前,你还需要先下载一份框架的预览发布版。可以用浏览器察看 http://framework.zend.com/download 并选择 tar.gz 或者 zip 文件手工下载,也可以使用下面的命令行:
清单1
$ wget http://framework.zend.com/download/tgz
$ tar -xvzf ZendFramework-0.1.2.tar.gz

注意
Zend已经计划提供一个独立的PEAR通道来方便下载。

下载了预览发布版之后,将这个库的目录放到一个方便的地方。在本教程中,我将库的目录名改称了lib,以便提供一个简单干净的目录结构:
清单2
app/
+-views/
+-controllers/
www/
+- .htaccess
+- index.php
lib/

www 目录是文档根目录,controllers和views目录为空,是将来要用的,lib目录是来自于下载的预览版。

入门

我第一个要向你展示的组件是Zend_Controller。在很多情况下,它为要开发的应用提供了一个基础,同时它也是令Zend Framework超越了组件集合的一个部分。不过在使用它之前,需要将所有进入的请求引导到某个PHP脚本中。本教程将使用mod_rewrite来完成这个目的。
如何用好mod_rewrite确实是一门艺术,不过还好本文中这个特殊的任务十分简单。如果你对mod_rewrite或者是Apache的一般配置还不是很熟悉的话,可以在文档根目录下创建一个.htaccess文件,并加入一下指令:
清单3
RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

Zend_Controller目前的任务之一就是去掉对mod_rewrite的依赖。为了提供一个预览版可以使用的例子,本教程便使用了mod_rewrite。
如果你直接在httpd.conf中添加这些指令,还必须重新启动Web服务。但是,如果使用.htaccess文件,就不用了,而且这样更好。你
可以随便在index.php中写点东西,然后任意请求某些路径来测试一下,比如/foo/bar。例如,如果你的主机是example.org,那么就
请求URL http://example.org/foo/bar
可能你还想在 include_path 中包含框架库的路径。你可以直接在php.ini中配置,或者可以将以下指令放入.htaccess文件中:
清单4
php_value include_path "/path/to/lib"

Zend

Zend 类包含了一系列十分通用也十分有用的静态方法。这是唯一一个需要手工进行包含的类:
清单5
view plainprint?<?php

include 'Zend.php';

?>
<?php
include 'Zend.php';
?>

一旦引用了Zend.php,就可以访问Zend类中的所有方法了。使用
loadClass()
方法,载入其他类也变得简单了。例如载入
Zend_Controller_Front
类:
清单6
view plainprint?<?php

include 'Zend.php';

Zend::loadClass('Zend_Controller_Front');

?>
<?php
include 'Zend.php';
Zend::loadClass('Zend_Controller_Front');
?>

loadClass()
方法会考虑到include_path,同时它还知道框架的目录组织结构。我就使用它来载入所有其他的类。

Zend_Controller

这个控制器的使用还是比较直观的。实际上,我写这份指南的时候可没有官方文档可用!
现在ZF网站上已经有官方文档了。
首先讲
Zend_Controller_Front
,这是一个前端控制器。你可以将下面的代码放入index.php中来理解它是如何工作的:
清单7
view plainprint?<?php

include 'Zend.php';

Zend::loadClass('Zend_Controller_Front');

$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory('/path/to/controllers');
$controller->dispatch();

?>
<?php
include 'Zend.php';
Zend::loadClass('Zend_Controller_Front');
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory('/path/to/controllers');
$controller->dispatch();
?>

如果你更希望使用对象链方式,可以如下改写:
清单8
view plainprint?<?php

include 'Zend.php';

Zend::loadClass('Zend_Controller_Front');

$controller = Zend_Controller_Front::getInstance()
->setControllerDirectory('/path/to/controllers')
->dispatch();
?>
<?php
include 'Zend.php';
Zend::loadClass('Zend_Controller_Front');
$controller = Zend_Controller_Front::getInstance()
->setControllerDirectory('/path/to/controllers')
->dispatch();
?>

现在,当进行/foo/bar的请求时,就会出现一个错误。这很好!它至少能告诉你有动作了。主要的问题是未发现
IndexController.php

在创建这个文件之前,最好首先了解框架组织东西的方式。框架会将一个请求分解成几个部分,在这个例子中,请求
/foo/bar
,foo是控制器,bar是动作。两者的默认值都是index。
当foo作为控制器时,框架首先在控制器目录中查找名叫
FooController.php
的文件。因为不存在这个文件,于是框架退一步查找IndexController.php。如果还是没有发现,就报告错误。
下面,在controllers目录(可以使用
setControllerDirectory()
自己设置)中创建
IndexController.php

清单9
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'IndexController::indexAction()';
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'IndexController::indexAction()';
}
}
?>

IndexController
类处理控制器为index的请求或者指定的控制器不存在的请求,就像刚才所说的。
indexAction()

法将处理动作为index的请求。记住无论是控制器还是动作,默认的值都是index,前面也说过了。如果尝试请求/、/index或者/index
/index,都会执行indexAction()方法(结尾的斜杠不会改变这种行为)。对任何其他资源的请求都可能会产生错误。
继续之前还要为IndexController添加一个很有用的方法noRouteAction()。一旦请求某个控制器且其不存在时便调用
noRouteAction()方法。例如,请求/foo/bar时,如果FooController.php不存在,那么就会执行
noRouteAction()。不过,/index/foo的请求还是会产生错误,因为这里foo是一个动作,而非控制器。
在IndexController中添加 noRouteAction() :
清单10
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'IndexController::indexAction()';
}

public function noRouteAction()
{
$this->_redirect('/');
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'IndexController::indexAction()';
}
public function noRouteAction()
{
$this->_redirect('/');
}
}
?>

这个例子使用了 $this->_redirect(’/') 来描述可以在noRouteAction()中一般可能出现的动作。这可令对不存在的控制器的请求被重定向到根文档(首页)。
现在来创建 FooController.php:
清单11
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class FooController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'FooController::indexAction()';
}

public function barAction()
{
echo 'FooController::barAction()';
}
}
?>
<?php
Zend::loadClass('Zend_Controller_Action');
class FooController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'FooController::indexAction()';
}
public function barAction()
{
echo 'FooController::barAction()';
}
}
?>

如果你再请求 /foo/bar,就应该看到执行了barAction(),因为请求的动作是bar。这样不仅可以支持友好的URL,同时也可以用极少的代码就可以很好得进行组织。酷啊!
还可以创建一个__call()方法来处理未定义的动作的请求,如 /foo/baz:
清单12
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class FooController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'FooController::indexAction()';
}

public function barAction()
{
echo 'FooController::barAction()';
}

public function __call($action, $arguments)
{
echo 'FooController:__call()';
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class FooController extends Zend_Controller_Action
{
public function indexAction()
{
echo 'FooController::indexAction()';
}
public function barAction()
{
echo 'FooController::barAction()';
}
public function __call($action, $arguments)
{
echo 'FooController:__call()';
}
}
?>

现在只需几行代码就可以很优雅地处理进入的请求了,让我们继续。

Zend_View

Zend_View
是一个可以协助你组织视图逻辑的类。它并不使用特定的模版系统,为了简便起见,在本例中我也不会使用模版系统。然而,你可以随意使用你喜欢的。
记住所有进入的请求都是由前端控制器来处理的。因此,既然应用程序的框架已经这样存在了,那么以后的天价都必须适应它。为了演示Zend_View最基本的用法,我们将IndexController.php中的代码修改成这样:
清单13
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');
Zend::loadClass('Zend_View');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$view = new Zend_View();
$view->setScriptPath('/path/to/views');
echo $view->render('example.php');
}

public function noRouteAction()
{
$this->_redirect('/');
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
Zend::loadClass('Zend_View');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$view = new Zend_View();
$view->setScriptPath('/path/to/views');
echo $view->render('example.php');
}
public function noRouteAction()
{
$this->_redirect('/');
}
}
?>

在视图目录(这里是views)创建一个叫做
example.php
的文件:
清单14 –
view plainprint?<html> <head> <title>This Is an Example</title> </head> <body> <p>This is an example.</p> </body> </html>
<html>
<head>
<title>This Is an Example</title>
</head>
<body>
<p>This is an example.</p>
</body>
</html>

现在,当请求网站的根的资源时,应该可以看到example.php的内容。虽然现在这还不是很有用,不过记住你的工作目标是按照一个结构化、有组织的方法来开发Web应用。
为了更清楚地利用
Zend_View
,将模版(example.php)修改一下,包含一些数据:
清单15
view plainprint?<html> <head> ? ? <title><?php echo $this->escape($this->title); ?></title> </head> <body> ? ? <?php echo $this->escape($this->body); ?> </body> </html>
<html>
<head>
? ? <title><?php echo $this->escape($this->title); ?></title>
</head>
<body>
? ? <?php echo $this->escape($this->body); ?>
</body>
</html>

添加了两个额外的特性。$this->escape()方法必须用在所有的输出上。即便你要自己创建输出(例如这个例子中的),也要将所有的输出进行转义,这种好习惯可以防止出现跨站脚本(XSS)。
$this->title
$this->body
特性在这里是用于演示动态数据的。它们应该在控制器中定义,所以让我们修改
IndexController.php
来给他们赋值:
清单16
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');
Zend::loadClass('Zend_View');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$view = new Zend_View();
$view->setScriptPath('/path/to/views');
$view->title = 'Dynamic Title';
$view->body = 'This is a dynamic body.';
echo $view->render('example.php');
}

public function noRouteAction()
{
$this->_redirect('/');
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
Zend::loadClass('Zend_View');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$view = new Zend_View();
$view->setScriptPath('/path/to/views');
$view->title = 'Dynamic Title';
$view->body = 'This is a dynamic body.';
echo $view->render('example.php');
}
public function noRouteAction()
{
$this->_redirect('/');
}
}
?>

现在你再浏览网站,应该看到了模版所使用的这些值。在模版中使用$this的原因是模版是在Zend_View的实例的范围内执行的。
记住example.php仅仅是一个普通的PHP脚本,所以你可以在其中做任意你想做的事情。最好还是尽量遵守规则,仅仅在模版中进行显示数据的工作。控制器(或者是控制器进行分配的模块)则应该承担所有的业务逻辑。
在继续讲之前,我要最后对Zend_View做一个补充。在每个控制器的方法中实例化$view对象会要额外输入很多东西,而我们的主要目标是更简单、更快速地进行开发。而且,如果模版都存放在同一个目录下的话,每次都要调用setScriptPath()也是一件麻烦事。
幸好,Zend类包含了一个注册表,它可以帮助我们消除这种反复的工作。你可以使用register()方法将$view对象存放在注册表中:
清单17
view plainprint?<?php

Zend::register('view', $view);

?>
<?php
Zend::register('view', $view);
?>

可以使用registry()方法来获取它:
清单18
view plainprint?<?php

$view = Zend::registry('view');

?>
<?php
$view = Zend::registry('view');
?>

从今往后,本教程就会使用注册表了。

Zend_InputFilter

The last component this tutorial covers is Zend_InputFilter. This
class provides a simple but rigid approach to input filtering. You
instantiate it by passing an array of data to be filtered:
清单19
view plainprint?<?php

$filterPost = new Zend_InputFilter($_POST);

?>
<?php
$filterPost = new Zend_InputFilter($_POST);
?>

他会把数组(
$_POST
)设置为NULL,这样就不可能再直接进行访问了。
Zend_InputFilter
提供了一些根据特定条件筛选数据的方法。例如,如果你需要
$_POST['name']
都是字母,可以使用
getAlpha()
方法:
清单20
view plainprint?<?php

/* $_POST{{'name'}} = 'John123Doe'; */

$filterPost = new Zend_InputFilter($_POST);

/* $_POST = NULL; */

$alphaName = $filterPost->getAlpha('name');
/* $alphaName = 'JohnDoe'; */

?>
<?php
/* $_POST{{'name'}} = 'John123Doe'; */
$filterPost = new Zend_InputFilter($_POST);
/* $_POST = NULL; */
$alphaName = $filterPost->getAlpha('name');
/* $alphaName = 'JohnDoe'; */
?>

传给每一个筛选方法的参数是对应要进行筛选的数组元素的键。该对象(在这个例子中是
$filterPost
)是一个包含了有错误的数据的保护笼,这使得对数据的访问更加可控和一致。因此,当要访问输入数据的时候,应该使用
Zend_InputFilter

Zend_Filter
提供了一些静态的过滤方法,这些方法和Zend_InputFilter的方法遵循同样的规则。

创建一个新闻管理系统

尽管预览版还包含了很多组件(甚至还有更多的正在进行开发),但是只需要使用前面讨论过的组件就可以构建简单的应用了。在构建应用的过程中,你就会对框架的基本结构和设计有一个更加清晰的理解。
每个人开发应用的方式都有所不同,所以Zend Framework尽可能地尝试包容这些差异。同样,本教程是根据我的偏好写的,所以你可以将它们调整为适合自己口味的方式。
当我开始开发某个应用时,我是先从界面开始的。这并不是说我喜欢做表面文章,花大量功夫在样式、图片上,其实我是站在一个用户的角度来透视问题。这样,我将一个应用看作是一系列页面的集合,每个页面对应一个唯一的URL。这个新闻管理系统有以下一些URL组成:
清单21
/
/add/news
/add/comment
/admin
/admin/approve
/view/{id}

马上开始根据控制器考虑这些URL。IndexController显示新闻、AddController处理新闻和评论的添加,AdminController处理诸如审批新闻之类的管理工作,以及ViewController用于查看指定的新闻条目和相应的评论。
首先,如果有FooController.php,先将其删除,并修改IndexController.php并添加合适的动作,并加入一些关于业务逻辑的注释放着:
清单22
view plainprint? <?php

Zend::loadClass('Zend_Controller_Action');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/* List the news. */
}

public function noRouteAction()
{
$this->_redirect('/');
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/* List the news. */
}
public function noRouteAction()
{
$this->_redirect('/');
}
}
?>

下面,创建AddController.php:
清单23
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class AddController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}

function commentAction()
{
/* Add a comment. */
}

function newsAction()
{
/* Add news. */
}

function __call($action, $arguments)
{
$this->_redirect('/');
}
}
?>
<?php
Zend::loadClass('Zend_Controller_Action');
class AddController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}
function commentAction()
{
/* Add a comment. */
}
function newsAction()
{
/* Add news. */
}
function __call($action, $arguments)
{
$this->_redirect('/');
}
}
?>

注意
AddController
indexAction()
不应被调用。只有当请求的路径是/add时才会调用这个方法。因为用户也许会手工输入URL,还是有可能会被调用的,所以这时应该将用户重定向到首页、显示一个错误或者你觉得合适的动作。
下面,创建AdminController.php:
清单24 –
view plainprint?<?php
Zend::loadClass('Zend_Controller_Action');

class AdminController extends Zend_Controller_Action
{
function indexAction()
{
/* Display admin interface. */
}

function approveAction()
{
/* Approve news. */
}

function __call($action, $arguments)
{
$this->_redirect('/');
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class AdminController extends Zend_Controller_Action
{
function indexAction()
{
/* Display admin interface. */
}
function approveAction()
{
/* Approve news. */
}
function __call($action, $arguments)
{
$this->_redirect('/');
}
}
?>

最后,创建ViewController.php:
清单25
view plainprint?<?php

Zend::loadClass('Zend_Controller_Action');

class ViewController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}

function __call($id, $arguments)
{
/* Display news and comments for $id. */
}
}

?>
<?php
Zend::loadClass('Zend_Controller_Action');
class ViewController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}
function __call($id, $arguments)
{
/* Display news and comments for $id. */
}
}
?>

和AddController中的一样,index()方法应该是不可能会被调用的,所以可以在其中安排任何动作。ViewController和其他的有些不同,因为还不知道什么是有效的动作。为了能支持类似/view/23这样的URL,必须使用__call()来支持动态动作。

与数据库进行交互

因为Zend Framework的数据库组件相对还不太稳定,同时我又希望例子更容易使用,所以我使用了SQLite的类来存储和获取新闻条目以及评论:
清单26
view plainprint?<?php

class Database
{
private $_db;

public function __construct($filename)
{
$this->_db = new SQLiteDatabase($filename);
}

public function addComment($name, $comment, $newsId)
{
$name = sqlite_escape_string($name);
$comment = sqlite_escape_string($comment);
$newsId = sqlite_escape_string($newsId);

$sql = "INSERT
INTO comments (name, comment, newsId)
VALUES ('$name', '$comment', '$newsId')";

return $this->_db->query($sql);
}

public function addNews($title, $content)
{
$title = sqlite_escape_string($title);
$content = sqlite_escape_string($content);

$sql = "INSERT
INTO news (title, content)
VALUES ('$title', '$content')";

return $this->_db->query($sql);
}

public function approveNews($ids)
{
foreach ($ids as $id) {
$id = sqlite_escape_string($id);

$sql = "UPDATE news
SET approval = 'T'
WHERE id = '$id'";

if (!$this->_db->query($sql)) {
return FALSE;
}
}

return TRUE;
}

public function getComments($newsId)
{
$newsId = sqlite_escape_string($newsId);

$sql = "SELECT name, comment
FROM comments
WHERE newsId = '$newsId'";

if ($result = $this->_db->query($sql)) {
return $result->fetchAll();
}

return FALSE;
}

public function getNews($id = 'ALL')
{
$id = sqlite_escape_string($id);

switch ($id) {
case 'ALL':
$sql = "SELECT id,
title
FROM news
WHERE approval = 'T'";
break;
case 'NEW':
$sql = "SELECT *
FROM news
WHERE approval != 'T'";
break;
default:
$sql = "SELECT *
FROM news
WHERE id = '$id'";
break;
}

if ($result = $this->_db->query($sql)) {
if ($result->numRows() != 1) {
return $result->fetchAll();
} else {
return $result->fetch();
}
}

return FALSE;
}
}

?>
<?php
class Database
{
private $_db;
public function __construct($filename)
{
$this->_db = new SQLiteDatabase($filename);
}
public function addComment($name, $comment, $newsId)
{
$name = sqlite_escape_string($name);
$comment = sqlite_escape_string($comment);
$newsId = sqlite_escape_string($newsId);
$sql = "INSERT
INTO   comments (name, comment, newsId)
VALUES ('$name', '$comment', '$newsId')";
return $this->_db->query($sql);
}
public function addNews($title, $content)
{
$title = sqlite_escape_string($title);
$content = sqlite_escape_string($content);
$sql = "INSERT
INTO   news (title, content)
VALUES ('$title', '$content')";
return $this->_db->query($sql);
}
public function approveNews($ids)
{
foreach ($ids as $id) {
$id = sqlite_escape_string($id);
$sql = "UPDATE news
SET    approval = 'T'
WHERE  id = '$id'";
if (!$this->_db->query($sql)) {
return FALSE;
}
}
return TRUE;
}
public function getComments($newsId)
{
$newsId = sqlite_escape_string($newsId);
$sql = "SELECT name, comment
FROM   comments
WHERE  newsId = '$newsId'";
if ($result = $this->_db->query($sql)) {
return $result->fetchAll();
}
return FALSE;
}
public function getNews($id = 'ALL')
{
$id = sqlite_escape_string($id);
switch ($id) {
case 'ALL':
$sql = "SELECT id,
title
FROM   news
WHERE  approval = 'T'";
break;
case 'NEW':
$sql = "SELECT *
FROM   news
WHERE  approval != 'T'";
break;
default:
$sql = "SELECT *
FROM   news
WHERE  id = '$id'";
break;
}
if ($result = $this->_db->query($sql)) {
if ($result->numRows() != 1) {
return $result->fetchAll();
} else {
return $result->fetch();
}
}
return FALSE;
}
}
?>

当然,你可以用自己的解决方案来替换这个类。包含它只为了提供一个完整的例子,并不是给出一个推荐的实现。
这个类的构造器需要获得SQLite数据库的完整路径和文件名,数据库必须事先创建好:
清单27
view plainprint?<?php

$db = new SQLiteDatabase('/path/to/db.sqlite');

$db->query("CREATE TABLE news (
id INTEGER PRIMARY KEY,
title VARCHAR(255),
content TEXT,
approval CHAR(1) DEFAULT 'F'
)");

$db->query("CREATE TABLE comments (
id INTEGER PRIMARY KEY,
name VARCHAR(255),
comment TEXT,
newsId INTEGER
)");

?>
<?php
$db = new SQLiteDatabase('/path/to/db.sqlite');
$db->query("CREATE TABLE news (
id       INTEGER PRIMARY KEY,
title    VARCHAR(255),
content  TEXT,
approval CHAR(1) DEFAULT 'F'
)");
$db->query("CREATE TABLE comments (
id       INTEGER PRIMARY KEY,
name     VARCHAR(255),
comment  TEXT,
newsId   INTEGER
)");
?>

这只需要运行一次,然后就只要将完整的路径和文件名传给Database类就行了:
清单28
view plainprint?<?php

$db = new Database('/path/to/db.sqlite');

?>
<?php
$db = new Database('/path/to/db.sqlite');
?>

整合

为了能将所有的东西放到一起,先在lib目录中创建Database.php,这样loadClass()就能找到它了。而index.php文件现在要实例化$view和$db并将它们存储在注册表中。也可以创建一个叫做__autoload()的函数来自动加载所有需要用到的类:
清单29
view plainprint?<?php

include 'Zend.php';

function __autoload($class)
{
Zend::loadClass($class);
}

$db = new Database('/path/to/db.sqlite');
Zend::register('db', $db);

$view = new Zend_View;
$view->setScriptPath('/path/to/views');
Zend::register('view', $view);

$controller = Zend_Controller_Front::getInstance()
->setControllerDirectory('/path/to/controllers')
->dispatch();

?>
<?php
include 'Zend.php';
function __autoload($class)
{
Zend::loadClass($class);
}
$db = new Database('/path/to/db.sqlite');
Zend::register('db', $db);
$view = new Zend_View;
$view->setScriptPath('/path/to/views');
Zend::register('view', $view);
$controller = Zend_Controller_Front::getInstance()
->setControllerDirectory('/path/to/controllers')
->dispatch();
?>

下面,在视图目录中创建一些简单的模版。index.php文件可以用于显示index视图:
清单30 –
view plainprint?<html> <head> <title>News</title> </head> <body> <h1>News</h1> <?php foreach ($this->news as $entry) { ?> <p> <a href="/view/<?php echo $this->escape($entry{{'id'}}); ?>"> <?php echo $this->escape($entry{{'title'}}); ?> </a> </p> <?php } ?> <h1>Add News</h1> <form action="/add/news" method="POST"> <p>Title:<br /><input type="text" name="title" /></p> <p>Content:<br /><textarea name="content"></textarea></p> <p><input type="submit" value="Add News" /></p> </form> </body> </html>
<html>
<head>
<title>News</title>
</head>
<body>
<h1>News</h1>
<?php foreach ($this->news as $entry) { ?>
<p>
<a href="/view/<?php echo $this->escape($entry{{'id'}}); ?>">
<?php echo $this->escape($entry{{'title'}}); ?>
</a>
</p>
<?php } ?>
<h1>Add News</h1>
<form action="/add/news" method="POST">
<p>Title:<br /><input type="text" name="title" /></p>
<p>Content:<br /><textarea name="content"></textarea></p>
<p><input type="submit" value="Add News" /></p>
</form>
</body>
</html>

view.php 模版可以用于显示特定的新闻条目:
清单31
view plainprint?<html> <head> <title> <?php echo $this->escape($this->news{{'title'}}); ?> </title> </head> <body> <h1> <?php echo $this->escape($this->news{{'title'}}); ?> </h1> <p> <?php echo $this->escape($this->news{{'content'}}); ?> </p> <h1>Comments</h1> <?php foreach ($this->comments as $comment) { ?> <p> <?php echo $this->escape($comment{{'name'}}); ?> writes: </p> <blockquote> <?php echo $this->escape($comment{{'comment'}}); ?> </blockquote> <?php } ?> <h1>Add a Comment</h1> <form action="/add/comment" method="POST"> <input type="hidden" name="newsId" value="<?php echo $this->escape($this->id); ?>" /> <p>Name:<br /><input type="text" name="name" /></p> <p>Comment:<br /><textarea name="comment"></textarea></p> <p><input type="submit" value="Add Comment" /></p> </form> </body> </html>
<html>
<head>
<title>
<?php echo $this->escape($this->news{{'title'}}); ?>
</title>
</head>
<body>
<h1>
<?php echo $this->escape($this->news{{'title'}}); ?>
</h1>
<p>
<?php echo $this->escape($this->news{{'content'}}); ?>
</p>
<h1>Comments</h1>
<?php foreach ($this->comments as $comment) { ?>
<p>
<?php echo $this->escape($comment{{'name'}}); ?> writes:
</p>
<blockquote>
<?php echo $this->escape($comment{{'comment'}}); ?>
</blockquote>
<?php } ?>
<h1>Add a Comment</h1>
<form action="/add/comment" method="POST">
<input type="hidden" name="newsId"
value="<?php echo $this->escape($this->id); ?>" />
<p>Name:<br /><input type="text" name="name" /></p>
<p>Comment:<br /><textarea name="comment"></textarea></p>
<p><input type="submit" value="Add Comment" /></p>
</form>
</body>
</html>

最后,admin.php模版可以用于审批新闻条目:
清单32
view plainprint?<html>
<head>
<title>News Admin</title>
</head>
<body>
<form action="/admin/approve" method="POST">
<?php foreach ($this->news as $entry) { ?>
<p>
<input type="checkbox" name="ids{{}}"
value="<?php echo $this->escape($entry{{'id'}}); ?>" />
<?php echo $this->escape($entry{{'title'}}); ?>
<?php echo $this->escape($entry{{'content'}}); ?>
</p>
<?php } ?>
<p>
Password:<br /><input type="password" name="password" />
</p>
<p><input type="submit" value="Approve" /></p>
</form>
</body>
</html>
<html>
<head>
<title>News Admin</title>
</head>
<body>
<form action="/admin/approve" method="POST">
<?php foreach ($this->news as $entry) { ?>
<p>
<input type="checkbox" name="ids{{}}"
value="<?php echo $this->escape($entry{{'id'}}); ?>" />
<?php echo $this->escape($entry{{'title'}}); ?>
<?php echo $this->escape($entry{{'content'}}); ?>
</p>
<?php } ?>
<p>
Password:<br /><input type="password" name="password" />
</p>
<p><input type="submit" value="Approve" /></p>
</form>
</body>
</html>

为了简单起见,就使用一个带密码的表单作为访问控制机制。
放好了这些模版之后,就只要将原来放在控制器中占着位置的注释替换成几行代码。例如,IndexController.php就变成了:
清单33
view plainprint?<?php

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/* List the news. */
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews();
echo $view->render('index.php');
}

public function noRouteAction()
{
$this->_redirect('/');
}
}

?>
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
/* List the news. */
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews();
echo $view->render('index.php');
}
public function noRouteAction()
{
$this->_redirect('/');
}
}
?>

组织好所有的东西之后,应用的首页的完整的业务逻辑就被减至四行代码。AddController.php还要再处理一下,需要更多的代码:
清单34
view plainprint?<?php

class AddController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}

function commentAction()
{
/* Add a comment. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
$name = $filterPost->getAlpha('name');
$comment = $filterPost->noTags('comment');
$newsId = $filterPost->getDigits('newsId');
$db->addComment($name, $comment, $newsId);
$this->_redirect("/view/$newsId");
}

function newsAction()
{
/* Add news. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
$title = $filterPost->noTags('title');
$content = $filterPost->noTags('content');
$db->addNews($title, $content);
$this->_redirect('/');
}

function __call($action, $arguments)
{
$this->_redirect('/');
}
}

?>
<?php
class AddController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}
function commentAction()
{
/* Add a comment. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
$name = $filterPost->getAlpha('name');
$comment = $filterPost->noTags('comment');
$newsId = $filterPost->getDigits('newsId');
$db->addComment($name, $comment, $newsId);
$this->_redirect("/view/$newsId");
}
function newsAction()
{
/* Add news. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
$title = $filterPost->noTags('title');
$content = $filterPost->noTags('content');
$db->addNews($title, $content);
$this->_redirect('/');
}
function __call($action, $arguments)
{
$this->_redirect('/');
}
}
?>

因为用户在提交了一个表单之后被重定向了,所以在这个控制器里面不需要视图。
在AdminController.php中,要处理两个动作,显示管理界面和审批新闻:
清单35
view plainprint?<?php

class AdminController extends Zend_Controller_Action
{
function indexAction()
{
/* Display admin interface. */
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews('NEW');
echo $view->render('admin.php');
}

function approveAction()
{
/* Approve news. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
if ($filterPost->getRaw('password') == 'mypass') {
$db->approveNews($filterPost->getRaw('ids'));
$this->_redirect('/');
} else {
echo 'The password is incorrect.';
}
}

function __call($action, $arguments)
{
$this->_redirect('/');
}
}

?>
<?php
class AdminController extends Zend_Controller_Action
{
function indexAction()
{
/* Display admin interface. */
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews('NEW');
echo $view->render('admin.php');
}
function approveAction()
{
/* Approve news. */
$filterPost = new Zend_InputFilter($_POST);
$db = Zend::registry('db');
if ($filterPost->getRaw('password') == 'mypass') {
$db->approveNews($filterPost->getRaw('ids'));
$this->_redirect('/');
} else {
echo 'The password is incorrect.';
}
}
function __call($action, $arguments)
{
$this->_redirect('/');
}
}
?>

最后是ViewController.php:
清单36
view plainprint?<?php

class ViewController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}

function __call($id, $arguments)
{
/* Display news and comments for $id. */
$id = Zend_Filter::getDigits($id);
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews($id);
$view->comments = $db->getComments($id);
$view->id = $id;
echo $view->render('view.php');
}
}

?>
<?php
class ViewController extends Zend_Controller_Action
{
function indexAction()
{
$this->_redirect('/');
}
function __call($id, $arguments)
{
/* Display news and comments for $id. */
$id = Zend_Filter::getDigits($id);
$db = Zend::registry('db');
$view = Zend::registry('view');
$view->news = $db->getNews($id);
$view->comments = $db->getComments($id);
$view->id = $id;
echo $view->render('view.php');
}
}
?>

这段代码提供了一个功能完整——虽然非常简单的——的新闻共享和评论的应用。最好的地方就是借助于框架优雅的设计,添加更多的功能十分简单,同时随着Zend Framework的逐渐程序,各方面都会变得更好。

更多资料

本指南仅仅是讲解了一些皮毛,还有一些其他的资源可以参考。除了官方手册之外,Rob Allen提供了一些他对于Zend Framework的详细感受,Richard Thomas也给出了一些有用的注释。如果你有自己的看法,可以在本页上留下留言说出自己的想法。

结语

不过还是能发现这个预览版有些粗糙,我自己写这个教程的时候,遇到过一些挫折。不过整体上来说,我认为Zend
Framework兑现了大部分承诺,同时所有的参数者依然在继续努力改进它。Chris Shiflett 是 Brain
Bulb——一个专于PHP开发和安全性的咨询公司—— 的主席,你可以阅读一下Chris的Blog或者访问Brain Bulb的网站
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Framework 教程 Zend