zend framework quickstart zend框架入门之创建工程(快速开始:一)

题记:国内关于Zend Framework的资料非常少,翻译zend framework一方面是希望自己能更好的理解MVC框架结构,在以后的开发中能够设计出更符合MVC思想的网站或程序,另一方面希望能和大家交流一下。很多地方翻译的时候,由于水平和时间有限,欠准确。大家发现不妥的,可以提出来,我来修正它。



创建一个工程

首先下载和解压缩zend框架

安装zend框架
最容易的方法是下载安装zend server。
zend server已经为Mac OSX, Windows, Fedora Core, and Ubuntu,以及其他OS本地安装了zend框架。

一旦安装完zend server, zend框架就可以在以下路径找到: /usr/local/zend/share/ZendFramework(linux),C:\Program Files\Zend\ZendServer\share\ZendFramework (windows). include_path已经设置好了。

另外,你也可以单独下载,并且记录下来文件的位置。

(可选),然后把library子目录加到php.ini中的include_path。

zend框架安装好了。


创建工程:
在你安装好的zend框架里,有个bin的子目录,包含zf.sh(for linux) 和zf.bat(for win).

记录下来脚本的绝对地址;
在Unix-like的操作系统里,你可能想要使用shell的alias功能:alias zf.sh=path/to/ZendFramework/bin/zf.sh;
在windows系统里,你可以把zf.bat的路径加入系统环境变量path。

进入你想要建立项目的目录,然后在command里运行以下命令:



  1. % zf create project quickstart
运行这个命令以后zf会建立一些基本的网站结构,包括初始化的controllers和views。
目录树看起来将是:

  1. quickstart
  2. |-- application
  3. |   |-- Bootstrap.php
  4. |   |-- configs
  5. |   |   `-- application.ini
  6. |   |-- controllers
  7. |   |   |-- ErrorController.php
  8. |   |   `-- IndexController.php
  9. |   |-- models
  10. |   `-- views
  11. |       |-- helpers
  12. |       `-- scripts
  13. |           |-- error
  14. |           |   `-- error.phtml
  15. |           `-- index
  16. |               `-- index.phtml
  17. |-- library
  18. |-- public
  19. |   |-- .htaccess
  20. |   `-- index.php
  21. `-- tests
  22.     |-- application
  23.     |   `-- bootstrap.php
  24.     |-- library
  25.     |   `-- bootstrap.php
  26.     `-- phpunit.xml
(以上是系统提供的,以下是我自己的,可能是因为版本不同,所以生成的目绿结构略有差别)
─application
│  │  Bootstrap.php
│  │  
│  ├─configs
│  │      application.ini
│  │      
│  ├─controllers
│  │      ErrorController.php
│  │      IndexController.php
│  │      
│  ├─models
│  └─views
│      ├─helpers
│      └─scripts
│          ├─error
│          │      error.phtml
│          │      
│          └─index
│                  index.phtml
│                  
├─docs
│      README.txt
│      
├─library
├─public
│      .htaccess
│      index.php
│      
└─tests
    │  bootstrap.php
    │  phpunit.xml
    │  
    ├─application
    │  └─controllers
    │          IndexControllerTest.php
    │          
    └─library

加入到这步,你依然还没有把zend framework加入到include_path(建议看看zend framework安装), 我们推荐你可以复制或者链接它到你的library目录。 或者你想递归的复制和链接 你的zend framework 的library/zend/ 安装目录到你的项目的library目录。

 On unix-like systems, 运行类似以下的命令:

  1. # Symlink:
  2. % cd library; ln -s path/to/ZendFramework/library/Zend .
  3.  
  4. # Copy:
  5. % cd library; cp -r path/to/ZendFramework/library/Zend .

在 Windows 系统里, 用资源管理器。

项目建好以后,主要需要理解bootstrap、configuration、action controllers和views.

 Bootstrap (引导程序)


 Bootstrap类定义了初始化的资源和组件。Zend Framework的Front Controller默认被初始化。它用application/controllers/作为默认的目录,在这个目录下查找action controllers。这个类看起来像:

    // application/Bootstrap.php
     
    class Bootstrapextends Zend_Application_Bootstrap_Bootstrap
    {
    }

配置

zend framework会生成一些配置,不过你需要自己根据实际情况配置你的应用。

默认的配置文件是application/configs/application.ini,包含一些基本的设置php环境的变量(例如,关闭和打开错误报告),声明bootstrap类的路径和其他类名,你的action controllers的路径。类似:


    ; application/configs/application.ini
     
    [production]
    phpSettings.display_startup_errors=0
    phpSettings.display_errors=0
    includePaths.library= APPLICATION_PATH "/../library"
    bootstrap.path= APPLICATION_PATH "/Bootstrap.php"
    bootstrap.class="Bootstrap"
    appnamespace="Application"
    resources.frontController.controllerDirectory= APPLICATION_PATH "/controllers"
    resources.frontController.params.displayExceptions=0
     
    [staging : production]
     
    [testing : production]
    phpSettings.display_startup_errors=1
    phpSettings.display_errors=1
     
    [development : production]
    phpSettings.display_startup_errors=1
    phpSettings.display_errors=1

关于这个文件,有几件事情需要注意。当使用INI格式的配置文件是,你能直接参考常量,然后展开他们;APPLICATION_PATH就是个常量。另外记住有几个部分需要定义:production,stagin,testing,和development.后面的三个从production继承了环境设置。在每个阶段的应用开发过程中,组织配置确保合适的设置是有效的是一个有用的方法。


Action Controllers 

你的应用的action controller包含你的应用的工作流,负责映射请求到合适model和view。

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.


action controller应该有一个以上的以Action为结尾的方法;这些方法可以通过web来请求。默认情况下,zend framework URL采用/controller/action的模式,controller映射到action controller名字(减去Controller的前缀),action映射到一个action方法(去掉Action的前缀)。

An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema/controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).


典型的,你总需要一个IndexController,这是一个回叫controller也是服务网站的主页,anErrorController用来说明如HTTP404错误和HTTP500错误(应用程序错误)。

Typically, you always need an IndexController, which is a fallback controller and which also serves the home page of the site, and anErrorController, which is used to indicate things such asHTTP 404 errors (controller or action not found) andHTTP 500 errors (application errors).


默认的 IndexController 如下:

The default IndexController is as follows:

    // application/controllers/IndexController.php
     
    class IndexController extends Zend_Controller_Action
    {
     
        public function init()
        {
            /* Initialize action controller here */
        }
     
        public function indexAction()
        {
            // action body
        }
    }


And the default ErrorController is as follows:

    // application/controllers/ErrorController.php
     
    class ErrorController extends Zend_Controller_Action
    {
     
        public function errorAction()
        {
            $errors = $this->_getParam('error_handler');
     
            switch ($errors->type) {
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
                case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
     
                    // 404 error -- controller or action not found
                    $this->getResponse()->setHttpResponseCode(404);
                    $this->view->message = 'Page not found';
                    break;
                default:
                    // application error
                    $this->getResponse()->setHttpResponseCode(500);
                    $this->view->message = 'Application error';
                    break;
            }
     
            $this->view->exception = $errors->exception;
            $this->view->request   = $errors->request;
        }
    }
IndexController没有任何代码,而ErrorController参考了view属性。

You'll note that (1) the IndexController contains no real code, and (2) theErrorController makes reference to a "view" property. That leads nicely into our next subject.


视图

Views

视图在zend framework里是用php写的。 View脚本放置于application/views/scripts/,使用controller的名字命名。在我们的这个例子中,我们有一个IndexController和一个ErrorController,这样在view的目录里有index和error子目录相对应;默认情况下,有两个文件,一个是index/index.phtml和error/error.phtml
view脚本可以包含任何你想要的标记,使用<?和?>来插入指令。


Views in Zend Framework are written in plain oldPHP. View scripts are placed inapplication/views/scripts/, where they are further categorized using the controller names. In our case, we have anIndexController and anErrorController, and thus we have correspondingindex/ anderror/ subdirectories within our view scripts directory. Within these subdirectories, you will then find and create view scripts that correspond to each controller action exposed; in the default case, we thus have the view scriptsindex/index.phtml anderror/error.phtml.

View scripts may contain any markup you want, and use the<?php opening tag and?> closing tag to insertPHP directives.

下面是我们默认安装的index/index.phtml view脚本

The following is what we install by default for theindex/index.phtml view script:

    <!-- application/views/scripts/index/index.phtml -->
    <style>
     
        a:link,
        a:visited
        {
            color: #0398CA;
        }
     
        span#zf-name
        {
            color: #91BE3F;
        }
     
        div#welcome
        {
            color: #FFFFFF;
            background-image: url(http://framework.zend.com/images/bkg_header.jpg);
            width:  600px;
            height: 400px;
            border: 2px solid #444444;
            overflow: hidden;
            text-align: center;
        }
     
        div#more-information
        {
            background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif);
            height: 100%;
        }
     
    </style>
    <div id="welcome">
        <h1>Welcome to the <span id="zf-name">Zend Framework!</span><h1 />
        <h3>This is your project's main page<h3 />
        <div id="more-information">
            <p>
                <img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" />
            </p>
     
            <p>
                Helpful Links: <br />
                <a href="http://framework.zend.com/">Zend Framework Website</a> |
                <a href="http://framework.zend.com/manual/en/">Zend Framework
                    Manual</a>
            </p>
        </div>
    </div>
    <="" span="">

The error/error.phtml view script is slightly more interesting as it uses somePHP conditionals:

    <!-- application/views/scripts/error/error.phtml -->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Zend Framework Default Application</title>
    </head>
    <body>
      <h1>An error occurred</h1>
      <h2><?php echo $this->message ?></h2>
     
      <?php if ('development' == $this->env): ?>
     
      <h3>Exception information:</h3>
      <p>
          <b>Message:</b> <?php echo $this->exception->getMessage() ?>
      </p>
     
      <h3>Stack trace:</h3>
      <pre><?php echo $this->exception->getTraceAsString() ?>
      </pre>
     
      <h3>Request Parameters:</h3>
      <pre><?php echo var_export($this->request->getParams(), 1) ?>
      </pre>
      <?php endif ?>
     
    </body>
    </html>

创建一个虚拟主机

Create a virtual host

为了快速开始,我们将使用apache 作为服务器。当然zend framework也可以完美的运行于其他的web服务器。

For purposes of this quick start, we will assume you are using the» Apache web server. Zend Framework works perfectly well with other web servers -- including Microsoft Internet Information Server, lighttpd, nginx, and more -- but most developers should be famililar with Apache at the minimum, and it provides an easy introduction to Zend Framework's directory structure and rewrite capabilities.

为了创建虚拟主机,你需要知道httpd.conf文件的位置,可能的位置在:

To create your vhost, you need to know the location of yourhttpd.conf file, and potentially where other configuration files are located. Some common locations:

  • /etc/httpd/httpd.conf (Fedora, RHEL, and others)

  • /etc/apache2/httpd.conf (Debian, Ubuntu, and others)

  • /usr/local/zend/etc/httpd.conf (Zend Server on *nix machines)

  • C:\Program Files\Zend\Apache2\conf (Zend Server on Windows machines)

Within your httpd.conf (orhttpd-vhosts.conf on some systems), you will need to do two things. First, ensure that theNameVirtualHost is defined; typically, you will set it to a value of "*:80". Second, define a virtual host:

  1. <VirtualHost *: 80 >
  2.     ServerName quickstart.local
  3.     DocumentRoot /path/to/quickstart/public
  4.  
  5.     SetEnv APPLICATION_ENV "development"
  6.  
  7.     <Directory /path/to/quickstart/public>
  8.         DirectoryIndex index.php
  9.         AllowOverride All
  10.         Order allow , deny
  11.         Allow from all
  12.     </Directory>
  13. </VirtualHost>

有几点需要注意。
第一,DocumentRoot 设置为我们项目的public子目录;这意味着仅仅这个目录下的文件能被apache访问。

There are several things to note. First, note that theDocumentRoot setting specifies thepublic subdirectory of our project; this means that only files under that directory can ever be served directly by the server.

第二,记住AllowOverride,Order,和Allow指令;这些是允许我们在项目里使用htaccess文件。

在开发期间,这是一个好的实践,当你改变了你网站的指令时不需要经常的重启web服务器;然而,在产品阶段,你很可能应该把htaccess里的文件写进服务器配置文件中,然后禁止它。


Second, note theAllowOverride,Order, andAllow directives; these are to allow us to usehtacess files within our project. During development, this is a good practice, as it prevents the need to constantly restart the web server as you make changes to your site directives; however, in production, you should likely push the content of yourhtaccess file into your server configuration and disable this.

第三,记住设置环境变量。我们这里做的就是为你的虚拟主机设置一个环境变量;这个变量将被放进index.pho中,并且用来设置APPLICATION_ENV常量。在产品阶段,你能忽略这个指令(在那些production的值的情况下)或者明确的设置为产品模式。

Third, note theSetEnv directive. What we are doing here is setting an environment variable for your virtual host; this variable will be picked up in theindex.php and used to set theAPPLICATION_ENV constant for our Zend Framework application. In production, you can omit this directive (in which case it will default to the value "production") or set it explicitly to "production".

最后,你需要在你的hosts文件里添加一个和你的服务器名字一致的指令。在*nix-like系统里,通常是/etc/hosts;在win系统里,在C:\WINDOWS\system32\drivers\etc可以找到。

忽略系统,添加如下一行:

Finally, you will need to add an entry in yourhosts file corresponding to the value you place in yourServerName directive. On *nix-like systems, this is usually/etc/hosts; on Windows, you'll typically find it in C:\WINDOWS\system32\drivers\etc. Regardless of the system, the entry will look like the following:

  1. 127.0.0.1 quickstart.local

Start your webserver (or restart it), and you should be ready to go.

 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值