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

要求

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

下载框架

在开始阅读本指南之前,你还需要先下载一份框架的预览发布版。可以用浏览器察看 [url]http://framework.zend.com/download[/url] 并选择 tar.gz 或者 zip 文件手工下载,也可以使用下面的命令行:
清单1
$ wget [url]http://framework.zend.com/download/tgz[/url]
$ 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 [url]http://example.org/foo/bar[/url]。
可能你还想在 include_path 中包含框架库的路径。你可以直接在php.ini中配置,或者可以将以下指令放入.htaccess文件中:
清单4
php_value include_path "/path/to/lib"

Zend

Zend 类包含了一系列十分通用也十分有用的静态方法。这是唯一一个需要手工进行包含的类:
清单5
  1. <?php  
  2.   
  3. include 'Zend.php';  
  4.   
  5. ?>  
<?php
include 'Zend.php';
?>
一旦引用了 Zend.php,就可以访问 Zend类中的所有方法了。使用 loadClass()方法,载入其他类也变得简单了。例如载入 Zend_Controller_Front类:
清单6
  1. <?php  
  2.   
  3. include 'Zend.php';  
  4.   
  5. Zend::loadClass('Zend_Controller_Front');  
  6.   
  7. ?>   
<?php
include 'Zend.php';
Zend::loadClass('Zend_Controller_Front');
?> 
loadClass()方法会考虑到 include_path,同时它还知道框架的目录组织结构。我就使用它来载入所有其他的类。

Zend_Controller

这个控制器的使用还是比较直观的。实际上,我写这份指南的时候可没有官方文档可用!
现在ZF网站上已经有 官方文档了。
首先讲 Zend_Controller_Front,这是一个前端控制器。你可以将下面的代码放入index.php中来理解它是如何工作的:
清单7
  1. <?php  
  2.   
  3. include 'Zend.php';  
  4.   
  5. Zend::loadClass('Zend_Controller_Front');  
  6.   
  7. $controller = Zend_Controller_Front::getInstance();  
  8. $controller->setControllerDirectory('/path/to/controllers');  
  9. $controller->dispatch();  
  10.   
  11. ?>   
<?php
include 'Zend.php';
Zend::loadClass('Zend_Controller_Front');
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory('/path/to/controllers');
$controller->dispatch();
?> 
如果你更希望使用对象链方式,可以如下改写:
清单8
  1. <?php  
  2.   
  3. include 'Zend.php';  
  4.   
  5. Zend::loadClass('Zend_Controller_Front');  
  6.   
  7. $controller = Zend_Controller_Front::getInstance()  
  8.                 ->setControllerDirectory('/path/to/controllers')  
  9.                 ->dispatch();  
  10. ?>   
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class IndexController extends Zend_Controller_Action  
  6. {  
  7.     public function indexAction()  
  8.     {  
  9.         echo 'IndexController::indexAction()';  
  10.     }  
  11. }  
  12.   
  13. ?>   
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class IndexController extends Zend_Controller_Action  
  6. {  
  7.     public function indexAction()  
  8.     {  
  9.         echo 'IndexController::indexAction()';  
  10.     }  
  11.   
  12.     public function noRouteAction()  
  13.     {  
  14.         $this->_redirect('/');  
  15.     }  
  16. }  
  17.   
  18. ?>  
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class FooController extends Zend_Controller_Action  
  6. {  
  7.     public function indexAction()  
  8.     {  
  9.         echo 'FooController::indexAction()';  
  10.     }  
  11.   
  12.     public function barAction()  
  13.     {  
  14.         echo 'FooController::barAction()';  
  15.     }  
  16. }  
  17. ?>   
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class FooController extends Zend_Controller_Action  
  6. {  
  7.     public function indexAction()  
  8.     {  
  9.         echo 'FooController::indexAction()';  
  10.     }  
  11.   
  12.     public function barAction()  
  13.     {  
  14.         echo 'FooController::barAction()';  
  15.     }  
  16.   
  17.     public function __call($action$arguments)  
  18.     {  
  19.         echo 'FooController:__call()';  
  20.     }  
  21. }  
  22.   
  23. ?>  
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4. Zend::loadClass('Zend_View');  
  5.   
  6. class IndexController extends Zend_Controller_Action  
  7. {  
  8.     public function indexAction()  
  9.     {  
  10.         $view = new Zend_View();  
  11.         $view->setScriptPath('/path/to/views');  
  12.         echo $view->render('example.php');  
  13.     }  
  14.   
  15.     public function noRouteAction()  
  16.     {  
  17.         $this->_redirect('/');  
  18.     }  
  19. }  
  20.   
  21. ?>  
<?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 –
  1. <html>  
  2. <head>  
  3.     <title>This Is an Example</title>  
  4. </head>  
  5. <body>  
  6.     <p>This is an example.</p>  
  7. </body>  
  8. </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
  1. <html>  
  2. <head>  
  3. ? ? <title><?php echo $this->escape($this->title); ?></title>  
  4. </head>  
  5. <body>  
  6. ? ? <?php echo $this->escape($this->body); ?>  
  7. </body>  
  8. </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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4. Zend::loadClass('Zend_View');  
  5.   
  6. class IndexController extends Zend_Controller_Action  
  7. {  
  8.     public function indexAction()  
  9.     {  
  10.         $view = new Zend_View();  
  11.         $view->setScriptPath('/path/to/views');  
  12.         $view->title = 'Dynamic Title';  
  13.         $view->body = 'This is a dynamic body.';  
  14.         echo $view->render('example.php');  
  15.     }  
  16.   
  17.     public function noRouteAction()  
  18.     {  
  19.         $this->_redirect('/');  
  20.     }  
  21. }  
  22.   
  23. ?>  
<?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
  1. <?php  
  2.   
  3. Zend::register('view'$view);  
  4.   
  5. ?>   
<?php
Zend::register('view', $view);
?> 
可以使用registry()方法来获取它:
清单18
  1. <?php  
  2.   
  3. $view = Zend::registry('view');  
  4.   
  5. ?>  
<?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
  1. <?php  
  2.   
  3. $filterPost = new Zend_InputFilter($_POST);  
  4.   
  5. ?>    
<?php
$filterPost = new Zend_InputFilter($_POST);
?>  
他会把数组( $_POST)设置为 NULL,这样就不可能再直接进行访问了。 Zend_InputFilter提供了一些根据特定条件筛选数据的方法。例如,如果你需要 $_POST['name']都是字母,可以使用 getAlpha()方法:
清单20
  1. <?php  
  2.   
  3. /* $_POST{{'name'}} = 'John123Doe'; */  
  4.   
  5. $filterPost = new Zend_InputFilter($_POST);  
  6.   
  7. /* $_POST = NULL; */  
  8.   
  9. $alphaName = $filterPost->getAlpha('name');  
  10. /* $alphaName = 'JohnDoe'; */  
  11.   
  12. ?>   
<?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
  1.  <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class IndexController extends Zend_Controller_Action  
  6. {  
  7.     public function indexAction()  
  8.     {  
  9.         /* List the news. */  
  10.     }  
  11.   
  12.     public function noRouteAction()  
  13.     {  
  14.         $this->_redirect('/');  
  15.     }  
  16. }  
  17.   
  18. ?>   
 <?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class AddController extends Zend_Controller_Action  
  6. {  
  7.     function indexAction()  
  8.     {  
  9.         $this->_redirect('/');  
  10.     }  
  11.   
  12.     function commentAction()  
  13.     {  
  14.         /* Add a comment. */  
  15.     }  
  16.   
  17.     function newsAction()  
  18.     {  
  19.         /* Add news. */  
  20.     }  
  21.   
  22.     function __call($action$arguments)  
  23.     {  
  24.         $this->_redirect('/');  
  25.     }  
  26. }  
  27. ?>  
<?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('/');
	}
}
?>
注意 AddControllerindexAction()不应被调用。只有当请求的路径是/add时才会调用这个方法。因为用户也许会手工输入URL,还是有可能会被调用的,所以这时应该将用户重定向到首页、显示一个错误或者你觉得合适的动作。
下面,创建AdminController.php:
清单24 –
  1. <?php  
  2. Zend::loadClass('Zend_Controller_Action');  
  3.   
  4. class AdminController extends Zend_Controller_Action  
  5. {  
  6.     function indexAction()  
  7.     {  
  8.         /* Display admin interface. */  
  9.     }  
  10.   
  11.     function approveAction()  
  12.     {  
  13.         /* Approve news. */  
  14.     }  
  15.   
  16.     function __call($action$arguments)  
  17.     {  
  18.         $this->_redirect('/');  
  19.     }  
  20. }  
  21.   
  22. ?>  
<?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
  1. <?php  
  2.   
  3. Zend::loadClass('Zend_Controller_Action');  
  4.   
  5. class ViewController extends Zend_Controller_Action  
  6. {  
  7.     function indexAction()  
  8.     {  
  9.         $this->_redirect('/');  
  10.     }  
  11.   
  12.     function __call($id$arguments)  
  13.     {  
  14.         /* Display news and comments for $id. */  
  15.     }  
  16. }  
  17.   
  18. ?>   
<?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
  1. <?php  
  2.   
  3. class Database  
  4. {  
  5.     private $_db;  
  6.   
  7.     public function __construct($filename)  
  8.     {  
  9.         $this->_db = new SQLiteDatabase($filename);  
  10.     }  
  11.   
  12.     public function addComment($name$comment$newsId)  
  13.     {  
  14.         $name = sqlite_escape_string($name);  
  15.         $comment = sqlite_escape_string($comment);  
  16.         $newsId = sqlite_escape_string($newsId);  
  17.   
  18.         $sql = "INSERT  
  19.                 INTO   comments (name, comment, newsId)  
  20.                 VALUES ('$name''$comment''$newsId')";  
  21.   
  22.         return $this->_db->query($sql);  
  23.     }  
  24.   
  25.     public function addNews($title$content)  
  26.     {  
  27.         $title = sqlite_escape_string($title);  
  28.         $content = sqlite_escape_string($content);  
  29.   
  30.         $sql = "INSERT  
  31.                 INTO   news (title, content)  
  32.                 VALUES ('$title''$content')";  
  33.   
  34.         return $this->_db->query($sql);  
  35.     }  
  36.   
  37.     public function approveNews($ids)  
  38.     {  
  39.         foreach ($ids as $id) {  
  40.             $id = sqlite_escape_string($id);  
  41.   
  42.             $sql = "UPDATE news  
  43.                     SET    approval = 'T'  
  44.                     WHERE  id = '$id'";  
  45.   
  46.             if (!$this->_db->query($sql)) {  
  47.                 return FALSE;  
  48.             }  
  49.         }  
  50.   
  51.         return TRUE;  
  52.     }  
  53.   
  54.     public function getComments($newsId)  
  55.     {  
  56.         $newsId = sqlite_escape_string($newsId);  
  57.   
  58.         $sql = "SELECT name, comment  
  59.                 FROM   comments  
  60.                 WHERE  newsId = '$newsId'";  
  61.   
  62.         if ($result = $this->_db->query($sql)) {  
  63.             return $result->fetchAll();  
  64.         }  
  65.   
  66.         return FALSE;  
  67.     }  
  68.   
  69.     public function getNews($id = 'ALL')  
  70.     {  
  71.         $id = sqlite_escape_string($id);  
  72.   
  73.         switch ($id) {  
  74.             case 'ALL':  
  75.                 $sql = "SELECT id,  
  76.                                title  
  77.                         FROM   news  
  78.                         WHERE  approval = 'T'";  
  79.                 break;  
  80.             case 'NEW':  
  81.                 $sql = "SELECT *  
  82.                         FROM   news  
  83.                         WHERE  approval != 'T'";  
  84.                 break;  
  85.             default:  
  86.                 $sql = "SELECT *  
  87.                         FROM   news  
  88.                         WHERE  id = '$id'";  
  89.                 break;  
  90.         }  
  91.   
  92.         if ($result = $this->_db->query($sql)) {  
  93.             if ($result->numRows() != 1) {  
  94.                 return $result->fetchAll();  
  95.             } else {  
  96.                 return $result->fetch();  
  97.             }  
  98.         }  
  99.   
  100.         return FALSE;  
  101.     }  
  102. }  
  103.   
  104. ?>  
<?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
  1. <?php  
  2.   
  3. $db = new SQLiteDatabase('/path/to/db.sqlite');  
  4.   
  5. $db->query("CREATE TABLE news (  
  6.                 id       INTEGER PRIMARY KEY,  
  7.                 title    VARCHAR(255),  
  8.                 content  TEXT,  
  9.                 approval CHAR(1) DEFAULT 'F'  
  10.             )");  
  11.   
  12. $db->query("CREATE TABLE comments (  
  13.                 id       INTEGER PRIMARY KEY,  
  14.                 name     VARCHAR(255),  
  15.                 comment  TEXT,  
  16.                 newsId   INTEGER  
  17.             )");  
  18.   
  19. ?>   
<?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
  1. <?php  
  2.   
  3. $db = new Database('/path/to/db.sqlite');  
  4.   
  5. ?>   
<?php
$db = new Database('/path/to/db.sqlite');
?> 

整合

为了能将所有的东西放到一起,先在lib目录中创建 Database.php,这样loadClass()就能找到它了。而 index.php文件现在要实例化 $view$db并将它们存储在注册表中。也可以创建一个叫做 __autoload()的函数来自动加载所有需要用到的类:
清单29
  1. <?php  
  2.   
  3. include 'Zend.php';  
  4.   
  5. function __autoload($class)  
  6. {  
  7.     Zend::loadClass($class);  
  8. }  
  9.   
  10. $db = new Database('/path/to/db.sqlite');  
  11. Zend::register('db'$db);  
  12.   
  13. $view = new Zend_View;  
  14. $view->setScriptPath('/path/to/views');  
  15. Zend::register('view'$view);  
  16.   
  17. $controller = Zend_Controller_Front::getInstance()  
  18.               ->setControllerDirectory('/path/to/controllers')  
  19.               ->dispatch();  
  20.   
  21. ?>  
<?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 –
  1. <html>  
  2. <head>  
  3.   <title>News</title>  
  4. </head>  
  5. <body>  
  6.   <h1>News</h1>  
  7.   <?php foreach ($this->news as $entry) { ?>  
  8.   <p>  
  9.     <a href="/view/<?php echo $this->escape($entry{{'id'}}); ?>">  
  10.     <?php echo $this->escape($entry{{'title'}}); ?>  
  11.     </a>  
  12.   </p>  
  13.   <?php } ?>  
  14.   <h1>Add News</h1>  
  15.   <form action="/add/news" method="POST">  
  16.   <p>Title:<br /><input type="text" name="title" /></p>  
  17.   <p>Content:<br /><textarea name="content"></textarea></p>  
  18.   <p><input type="submit" value="Add News" /></p>  
  19.   </form>  
  20. </body>  
  21. </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
  1. <html>  
  2. <head>  
  3.   <title>  
  4.     <?php echo $this->escape($this->news{{'title'}}); ?>  
  5.   </title>  
  6. </head>  
  7. <body>  
  8.   <h1>  
  9.     <?php echo $this->escape($this->news{{'title'}}); ?>  
  10.   </h1>  
  11.   <p>  
  12.     <?php echo $this->escape($this->news{{'content'}}); ?>  
  13.   </p>  
  14.   <h1>Comments</h1>  
  15.   <?php foreach ($this->comments as $comment) { ?>  
  16.   <p>  
  17.     <?php echo $this->escape($comment{{'name'}}); ?> writes:  
  18.   </p>  
  19.   <blockquote>  
  20.     <?php echo $this->escape($comment{{'comment'}}); ?>  
  21.   </blockquote>  
  22.   <?php } ?>  
  23.   <h1>Add a Comment</h1>  
  24.   <form action="/add/comment" method="POST">  
  25.   <input type="hidden" name="newsId"  
  26.     value="<?php echo $this->escape($this->id); ?>" />  
  27.   <p>Name:<br /><input type="text" name="name" /></p>  
  28.   <p>Comment:<br /><textarea name="comment"></textarea></p>  
  29.   <p><input type="submit" value="Add Comment" /></p>  
  30.   </form>  
  31. </body>  
  32. </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
  1. <html>  
  2. <head>  
  3.   <title>News Admin</title>  
  4. </head>  
  5. <body>  
  6.   <form action="/admin/approve" method="POST">  
  7.   <?php foreach ($this->news as $entry) { ?>  
  8.   <p>  
  9.     <input type="checkbox" name="ids{{}}"  
  10.     value="<?php echo $this->escape($entry{{'id'}}); ?>" />  
  11.     <?php echo $this->escape($entry{{'title'}}); ?>  
  12.     <?php echo $this->escape($entry{{'content'}}); ?>  
  13.   </p>  
  14.   <?php } ?>  
  15.   <p>  
  16.     Password:<br /><input type="password" name="password" />  
  17.   </p>  
  18.   <p><input type="submit" value="Approve" /></p>  
  19.   </form>  
  20. </body>  
  21. </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
  1. <?php  
  2.   
  3. class IndexController extends Zend_Controller_Action  
  4. {  
  5.     public function indexAction()  
  6.     {  
  7.         /* List the news. */  
  8.         $db = Zend::registry('db');  
  9.         $view = Zend::registry('view');  
  10.         $view->news = $db->getNews();  
  11.         echo $view->render('index.php');  
  12.     }  
  13.   
  14.     public function noRouteAction()  
  15.     {  
  16.         $this->_redirect('/');  
  17.     }  
  18. }  
  19.   
  20. ?>   
<?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
  1. <?php  
  2.   
  3. class AddController extends Zend_Controller_Action  
  4. {  
  5.     function indexAction()  
  6.     {  
  7.         $this->_redirect('/');  
  8.     }  
  9.   
  10.     function commentAction()  
  11.     {  
  12.         /* Add a comment. */  
  13.         $filterPost = new Zend_InputFilter($_POST);  
  14.         $db = Zend::registry('db');  
  15.         $name = $filterPost->getAlpha('name');  
  16.         $comment = $filterPost->noTags('comment');  
  17.         $newsId = $filterPost->getDigits('newsId');  
  18.         $db->addComment($name$comment$newsId);  
  19.         $this->_redirect("/view/$newsId");  
  20.     }  
  21.   
  22.     function newsAction()  
  23.     {  
  24.         /* Add news. */  
  25.         $filterPost = new Zend_InputFilter($_POST);  
  26.         $db = Zend::registry('db');  
  27.         $title = $filterPost->noTags('title');  
  28.         $content = $filterPost->noTags('content');  
  29.         $db->addNews($title$content);  
  30.         $this->_redirect('/');  
  31.     }  
  32.   
  33.     function __call($action$arguments)  
  34.     {  
  35.         $this->_redirect('/');  
  36.     }  
  37. }  
  38.   
  39. ?>   
<?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
  1. <?php  
  2.   
  3. class AdminController extends Zend_Controller_Action  
  4. {  
  5.     function indexAction()  
  6.     {  
  7.         /* Display admin interface. */  
  8.         $db = Zend::registry('db');  
  9.         $view = Zend::registry('view');  
  10.         $view->news = $db->getNews('NEW');  
  11.         echo $view->render('admin.php');  
  12.     }  
  13.   
  14.     function approveAction()  
  15.     {  
  16.         /* Approve news. */  
  17.         $filterPost = new Zend_InputFilter($_POST);  
  18.         $db = Zend::registry('db');  
  19.         if ($filterPost->getRaw('password') == 'mypass') {  
  20.             $db->approveNews($filterPost->getRaw('ids'));  
  21.             $this->_redirect('/');  
  22.         } else {  
  23.             echo 'The password is incorrect.';  
  24.         }  
  25.     }  
  26.   
  27.     function __call($action$arguments)  
  28.     {  
  29.         $this->_redirect('/');  
  30.     }  
  31. }  
  32.   
  33. ?>   
<?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
  1. <?php  
  2.   
  3. class ViewController extends Zend_Controller_Action  
  4. {  
  5.     function indexAction()  
  6.     {  
  7.         $this->_redirect('/');  
  8.     }  
  9.   
  10.     function __call($id$arguments)  
  11.     {  
  12.         /* Display news and comments for $id. */  
  13.         $id = Zend_Filter::getDigits($id);  
  14.         $db = Zend::registry('db');  
  15.         $view = Zend::registry('view');  
  16.         $view->news = $db->getNews($id);  
  17.         $view->comments = $db->getComments($id);  
  18.         $view->id = $id;  
  19.         echo $view->render('view.php');  
  20.     }  
  21. }  
  22.   
  23. ?>   
<?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的网站