Documentation/zh_CN/book/1.0/02-Exploring-Symfony-s-Code (diff)

You must first sign up to be able to contribute.

Changes between Version 2 and Version 3 of Documentation/zh_CN/book/1.0/02-Exploring-Symfony-s-Code

Le.Jiang (IP:
03/06/07 17:42:21 (11 years ago)



  • Documentation/zh_CN/book/1.0/02-Exploring-Symfony-s-Code

    v2 v3  
    419 Now that you know the different components of a symfony application, you're probably wondering how they are organized. Symfony organizes code in a project structure and puts the project files into a standard tree structure. 
    421 ### Project Structure: Applications, Modules, and Actions 
    423 In symfony, a project is a set of services and operations available under a given domain name, sharing the same object model. 
    425 Inside a project, the operations are grouped logically into applications. An application can normally run independently of the other applications of the same project. In most cases, a project will contain two applications: one for the front-office and one for the back-office, sharing the same database. But you can also have one project containing many mini-sites, with each site as a different application. Note that hyperlinks between applications must be in the absolute form. 
    427 Each application is a set of one or more modules. A module usually represents a page or a group of pages with a similar purpose. For example, you might have the modules home, articles, `help`, `shoppingCart`, `account`, and so on. 
    429 Modules hold actions, which represent the various actions that can be done in a module. For example, a `shoppingCart` module can have `add`, `show`, and `update` actions. Generally, actions can be described by a verb. Dealing with actions is almost like dealing with pages in a classic web application, although two actions can result in the same page (for instance, adding a comment to a post in a weblog will redisplay the post with the new comment). 
     421### 项目结构: 应用程序,模块与动作 Project Structure: Applications, Modules, and Actions 
     427每个应用程序由一个或更多模块组成。模块就是功能相近的一个页面或者一组页面。例如,模块 home ,articles, `help`, `shoppingCart`, `account` 等。 
    432 >If this represents too many levels for a beginning project, it is very easy to group all actions into one single module, so that the file structure can be kept simple. When the application gets more complex, it will be time to organize actions into separate modules. As mentioned in Chapter 1, rewriting code to improve its structure or readability (but preserving its behavior) is called refactoring, and you will do this a lot when applying RAD principles. 
    434 Figure 2-3 shows a sample code organization for a weblog project, in a project/ application/module/action structure. But be aware that the actual file tree structure of the project will differ from the setup shown in the figure. 
    436 Figure 2-3 - Example of code organization 
    438 ![Example of code organization](/images/book/F0203.png "Example of code organization") 
     434图 2-3 是一个blog项目的代码组织结构图,按照项目/应用程序/模块/动作来划分。 但注意项目的实际文件结构可能会与图里面的不一样。 
     436图 2-3 - 代码组织结构例子 
     438![代码组织结构例子](/images/book/F0203.png "代码组织结构例子") 
    440440### 目录结构 
    442 All web projects generally share the same types of contents, such as the following
    444   * A database, such as MySQL or PostgreSQL 
    445   * Static files (HTML, images, JavaScript files, style sheets, and so on
    446   * Files uploaded by the site users and administrators 
    447   * PHP classes and libraries 
    448   * Foreign libraries (third-party scripts
    449   * Batch files (scripts to be launched by a command line or via a cron table
    450   * Log files (traces written by the application and/or the server
    451   * Configuration files 
    453 Symfony provides a standard file tree structure to organize all these contents in a logical way, consistent with the architecture choices (MVC pattern and project/application/module grouping). This is the tree structure that is automatically created when initializing every project, application, or module. Of course, you can customize it completely, to reorganize the files and directories at your convenience or to match your client's requirements. 
     444  * 一个数据库,例如MySQL或者PostgreSQL 
     445  * 静态文件(HTML, 图片, JavaScript文件,样式表等
     446  * 网站管理员与用户上传的文件 
     447  * PHP类与函数库 
     448  * 外部库(第三方脚本
     449  * 批处理文件 (用于命令行或者cron的脚本
     450  * 日志文件 (应用程序或者服务器的留下的脚印
     451  * 配置文件 
    455455#### 根目录结构 
    457 These are the directories found at the root of a symfony project
    459459    apps/ 
    479479      uploads/ 
    481 Table 2-1 describes the contents of these directories. 
    483 Table 2-1 - Root Directories 
    485 Directory  |  Description 
     481表 2-1 介绍这些目录的内容 
     483表 2-1 - 根目录 
     485目录  |  描述 
    486486---------- | ------------ 
    487 `apps/`    | Contains one directory for each application of the project (typically, `frontend` and `backend` for the front and back office). 
    488 `batch/`   | Contains PHP scripts called from a command line or a scheduler, to run batch processes. 
    489 `cache/`   | Contains the cached version of the configuration, and (if you activate it) the cache version of the actions and templates of the project. The cache mechanism (detailed in Chapter 12) uses these files to speed up the answer to web requests. Each application will have a subdirectory here, containing preprocessed PHP and HTML files. 
    490 `config/`  | Holds the general configuration of the project. 
    491 `data/`    | Here, you can store the data files of the project, like a database schema, a SQL file that creates tables, or even a SQLite database file. 
    492 `doc/`     | Stores the project documentation, including your own documents and the documentation generated by PHPdoc. 
    493 `lib/`     | Dedicated to foreign classes or libraries. Here, you can add the code that needs to be shared among your applications. The `model/` subdirectory stores the object model of the project (described in Chapter 8). 
    494 `log/`     | Stores the applicable log files generated directly by symfony. It can also contain web server log files, database log files, or log files from any part of the project. Symfony creates one log file per application and per environment (log files are discussed in Chapter 16). 
    495 `plugins/` | Stores the plug-ins installed in the application (plug-ins are discussed in Chapter 17). 
    496 `test/`    | Contains unit and functional tests written in PHP and compatible with the symfony testing framework (discussed in Chapter 15). During the project setup, symfony automatically adds some stubs with a few basic tests. 
    497 `web/`     | The root for the web server. The only files accessible from the Internet are the ones located in this directory. 
    499 #### Application目录结构 Application Tree Structure 
    501 The tree structure of all application directories is the same
     487`apps/`    | 包含此项目内所有应用程序(一般情况, `frontend` 与 `backend` 分别代表前台与后台). 
     488`batch/`   | 包含命令行下运行的PHP脚本或者定期执行的脚本 
     489`cache/`   | 包含了配置文件的缓存,如果你开了动作和模版,还有这两个部分的缓存。缓存机制(详见第12章)把这些信息存在文件里面加快响应web请求的速度。每个应用程序都会有一个子目录,包含了预处理的PHP与HTML文件。 
     490`config/`  | 存放项目的配置信息。 
     491`data/`    | 这里是你可以存放项目的数据文件,例如数据库schema,包含了建立数据表的SQL文件,或者一个SQLite数据库文件。 
     492`doc/`     | 存放项目文档,包括你自己的文档和PHPdoc生成的文档。 
     493`lib/`     | 主要用来存放外部类或者库。这里的内容整个项目都能访问到。'model/`子目录存放项目的对象模型(详见第8章)。 
     494`log/`     | 存放symfony生成的应用程序的日志文件。也可以放web服务器的日志文件,数据库日志文件,或者项目的任何地方的日志文件。symfony自动为项目的每一个应用程序的每一个环境生成一个日志文件(l日志文件详见第16章). 
     495`plugins/` | 存放安装在项目里的插件(插件详见第17章)。 
     496`test/`    | 包含PHP写的与symfony测试框架兼容的单元与功能测试(详见第15章)。 项目初始化的时候,symfony会自动建立一些基本的测试。 
     497`web/`     | web服务器的根目录。所有从因特网能够直接访问的文件都在这个目录里。 
     499#### 应用程序目录结构 Application Tree Structure 
    503503    apps/ 
    504       [application name]/ 
     504      [应用程序名]/ 
    505505        config/ 
    506506        i18n/ 
    512512          error.txt 
    514 Table 2-2 describes the application subdirectories. 
    516 Table 2-2 - Application Subdirectories 
    518 Directory    | Description 
     514表 2-2 介绍应用程序的子目录 
     516表 2-2 - 应用程序的子目录 
     518目录    | 描述 
    519519------------ | ----------- 
    520 `config/`    | Holds a hefty set of YAML configuration files. This is where most of the application configuration is, apart from the default parameters that can be found in the framework itself. Note that the default parameters can still be overridden here if needed. You'll learn more about application configuration in the Chapter 5. 
    521 `i18n/`      | Contains files used for the internationalization of the application--mostly interface translation files (Chapter 13 deals with internationalization). You can bypass this directory if you choose to use a database for internationalization. 
    522 `lib/`       | Contains classes and libraries that are specific to the application. 
    523 `modules/`   | Stores all the modules that contain the features of the application. 
    524 `templates/` | Lists the global templates of the application--the ones that are shared by all modules. By default, it contains a `layout.php` file, which is the main layout in which the module templates are inserted. 
    526 >**NOTE** 
    527 >The `i18n/`, `lib/`, and `modules/` directories are empty for a new application. 
    529 The classes of an application are not able to access methods or attributes in other applications of the same project. Also note that hyperlinks between two applications of the same project must be in absolute form. You need to keep this last constraint in mind during initialization, when you choose how to divide your project into applications. 
     520`config/`    | 包含一些YAML格式的配置文件。大部分应用程序的配置信息都在这里,symfony框架自己的默认配置除外。 注意需要的话默认值可以修改。详见第5章。 
     521`i18n/`      | 包含应用程序的国际化文件--大部分的界面翻译文件(详见第13章)。如果你用数据库存放翻译信息可以忽略这个目录。 
     522`lib/`       | 包含应用程序用到的类与库。 
     523`modules/`   | 存放应用程序的所有功能模块。 
     524`templates/` | 包含应用程序的全局模版--所有模块公用的模版。默认情况,这个目录会有一个`layout.php`文件,这是模块模版默认主布局。 
     527>新应用程序的`i18n/`, `lib/`, 与 `modules/` 目录是空的。 
    531531#### 模块目录结构 Module Tree Structure 
    533 Each application contains one or more modules. Each module has its own subdirectory in the `modules` directory, and the name of this directory is chosen during the setup. 
    535 This is the typical tree structure of a module
    537537    apps/ 
    538       [application name]/ 
     538      [应用程序名]/ 
    539539        modules/ 
    540           [module name]/ 
     540          [模块名]/ 
    541541              actions/ 
    542542                actions.class.php 
    547547              validate/ 
    549 Table 2-3 describes the module subdirectories. 
    551 Table 2-3 -  Module Subdirectories 
    553 Directory    | Description 
     549表 2-3 介绍模块子目录 
     551表 2-3 -  模块子目录 
     553目录    | 描述 
    554554------------ | ------------ 
    555 `actions/`   | Generally contains a single class file named `actions.class.php`, in which you can store all the actions of the module. You can also write different actions of a module in separate files. 
    556 `config/`    | Can contain custom configuration files with local parameters for the module. 
    557 `lib/`       | Stores classes and libraries specific to the module. 
    558 `templates/` | Contains the templates corresponding to the actions of the module. A default template, called `indexSuccess.php`, is created during module setup. 
    559 `validate/`  | Dedicated to configuration files used for form validation (discussed in Chapter 10). 
    561 >**NOTE** 
    562 >The `config/`, `lib/`, and `validate/` directories are empty for a new module. 
    564 #### Web目录结构 
    566 There are very few constraints for the `web` directory, which is the directory of publicly accessible files. Following a few basic naming conventions will provide default behaviors and useful shortcuts in the templates. Here is an example of a `web` directory structure
     555`actions/`   | 一般只有一个文件`actions.class.php`,这个文件里面包含了模块的所有动作。模块的不同动作也可以分开写在不同的文件里。 
     556`config/`    | 可以存放与模块的配置信息。 
     557`lib/`       | 存放模块的类与库。 
     558`templates/` | 存放模块里所有动作的模版。模块初始化的时候,会建立一个默认模版`indexSuccess.php`。 
     559`validate/`  | 用户存放表单验证配置信息(详见第10章)。 
     562>新模块的`config/`, `lib/`, 与`validate/` 目录是空的 
     564#### web目录结构 
    568568    web/ 
    572572      uploads/ 
    574 Conventionally, the static files are distributed in the directories listed in Table 2-4. 
    576 Table 2-4 - Typical Web Subdirectories 
    578 Directory  | Description 
     574表 2-4 介绍web目录的内容 
     576表 2-4 - 典型的web目录的子目录 
     578目录  | 描述 
    579579---------- | ----------- 
    580 `css/`     | Contains style sheets with a `.css` extension. 
    581 `images/`  | Contains images with a `.jpg`, `.png`, or `.gif` format. 
    582 `js/`      | Holds JavaScript files with a `.js` extension. 
    583 `uploads/` | Must contain the files uploaded by the users. Even though the directory usually contains images, it is distinct from the images directory so that the synchronization of the development and production servers does not affect the uploaded images. 
    585 >**NOTE** 
    586 >Even though it is highly recommended that you maintain the default tree structure, it is possible to modify it for specific needs, such as to allow a project to run in a server with different tree structure rules and coding conventions. Refer to Chapter 19 for more information about modifying the file tree structure. 
     580`css/`     | 存放`.css`结尾的样式表文件 
     581`images/`  | 存放`.jpg`,`.png`与`.gif`扩展名的图片文件。 
     582`js/`      | 存放`.js`扩展名的JavaScript文件 
     583`uploads/` | 只能存放用户上传的文件。虽然这个目录通常会存放图片我们还是把这个目录与图片目录分开,这样同步开发服务器与正式服务器的时候不会影响上传的文件。 
    588588常用工具 Common Instruments 
    591 A few techniques are used repeatedly in symfony, and you will meet them quite often in this book and in your own projects. These include parameter holders, constants, and class autoloading. 
    593 ### Parameter Holders 
    595 Many of the symfony classes contain a parameter holder. It is a convenient way to encapsulate attributes with clean getter and setter methods. For instance, the sfResponse class holds a parameter holder that you can retrieve by calling the `getParameterHolder()` method. Each parameter holder stores data the same way, as illustrated in Listing 2-15. 
    597 Listing 2-15 - Using the `sfResponse` Parameter Holder 
     593### 参数 holder Parameter Holders 
     597例 2-15 - 使用 `sfResponse` 参数holder 
    599599    [php] 
    602602     => 'bar' 
    604 Most of the classes using a parameter holder provide proxy methods to shorten the code needed for get/set operations. This is the case for the `sfResponse` object, so you can do the same as in Listing 2-15 with the code of Listing 2-16. 
    606606Listing 2-16 - Using the `sfResponse` Parameter Holder Proxy Methods 
    611611     => 'bar' 
    613 The parameter holder getter accepts a default value as a second argument. This provides a useful fallback mechanism that is much more concise than possible with a conditional statement. See Listing 2-17 for an example. 
    615 Listing 2-17 - Using the Attribute Holder Getter's Default Value 
    617     [php] 
    618     // The 'foobar' parameter is not defined, so the getter returns an empty value 
     615例 2-17 - 使用参数holder的get方法的默认值 
     617    [php] 
     618    // 'foobar' 参数没有定义, 所以getter返回空值 
    619619    echo $response->getParameter('foobar'); 
    620620     => null 
    622     // A default value can be used by putting the getter in a condition 
     622    // 利用条件判断给一个默认值 
    623623    if ($response->hasParameter('foobar')) 
    624624    { 
    631631     => default 
    633     // But it is much faster to use the second getter argument for that 
     633    // 但是使用第二个默认值参数快的多 
    634634    echo $response->getParameter('foobar', 'default'); 
    635635     => default 
    637 The parameter holders even support namespaces. If you specify a third argument to a setter or a getter, it is used as a namespace, and the parameter will be defined only within that namespace. Listing 2-18 shows an example. 
    639 Listing 2-18 - Using the `sfResponse` Parameter Holder Namespace 
     639例 2-18 - `sfResponse` 参数 Holder 的名称空间 
    641641    [php] 
    647647     => 'bar2' 
    649 Of course, you can add a parameter holder to your own classes to take advantage of its syntax facilities. Listing 2-19 shows how to define a class with a parameter holder. 
    651 Listing 2-19 - Adding a Parameter Holder to a Class 
     651例 2-19 - 给类增加参数holder 
    653653    [php] 
    670670### 常量 Constants 
    672 Surprisingly, you will find very few constants in symfony. This is because constants have a major drawback in PHP: you can't change their value once they are defined. So symfony uses its own configuration object, called sfConfig, which replaces constants. It provides static methods to access parameters from everywhere. Listing 2-20 demonstrates the use of sfConfig class methods. 
    674 Listing 2-20 - Using the `sfConfig` Class Methods Instead of Constants 
    676     [php] 
    677     // Instead of PHP constants, 
     674例 2-20 - 使用 `sfConfig` 类方法取代常量 
     676    [php] 
     677    // PHP常量 
    678678    define('SF_FOO', 'bar'); 
    679679    echo SF_FOO; 
    680     // Symfony uses the sfConfig object 
     680    // symfony 使用sfConfig对象 
    681681    sfConfig::set('sf_foo', 'bar'); 
    682682    echo sfConfig::get('sf_foo'); 
    684 The sfConfig methods support default values, and you can call the sfConfig::set() method more than once on the same parameter to change its value. Chapter 5 discusses `sfConfig` methods in more detail. 
    686 ### 自动载入类 Class Autoloading 
    688 Classically, when you use a class method or create an object in PHP, you need to include the class definition first. 
     686### 类自动载入 Class Autoloading 
    690690    [php] 
    692692    $myObject = new MyClass(); 
    694 But on large projects with many classes and a deep directory structure, keeping track of all the class files to include and their paths takes a lot of time. By providing an __autoload() function (or a `spl_autoload_register()` function), symfony makes `include` statements unnecessary, and you can write directly: 
    696696    [php] 
    697697    $myObject = new MyClass(); 
    699 Symfony will then look for a `MyClass` definition in all files ending with `php` in one of the project's `lib/` directories. If the class definition is found, it will be included automatically. 
    701 So if you store all your classes in lib/ directories, you don't need to include classes anymore. That's why the symfony projects usually do not contain any `include` or `require` statements. 
    703 >**NOTE** 
    704 >For better performance, the symfony autoloading scans a list of directories (defined in an internal configuration file) during the first request. It then registers all the classes these directories contain and stores the class/file correspondence in a PHP file as an associative array. That way, future requests don't need to do the directory scan anymore. This is why you need to clear the cache every time you add or move a class file in your project by calling the `symfony clear-cache` command. You will learn more about the cache in Chapter 12, and about the autoloading configuration in Chapter 19. 
     704>为了提高效率,第一次symfony自动在一个目录列表(在配置文件里面定义)里寻找。然后symfony把这些目录里的所有类和文件的关联存放在一个PHP数组里。这样,以后的自动载入就不需要扫描整个目录了。所以你每次在项目里面增加一个类都需要通过`symfony clear-cache`命令清空symfony缓存。缓存详见第12章,自动载入配置文件详见第19章。 
    709 Using an MVC framework forces you to divide and organize your code according to the framework conventions. Presentation code goes to the view, data manipulation code goes to the model, and the request manipulation logic goes to the controller. It makes the application of the MVC pattern both very helpful and quite restricting. 
    711 Symfony is an MVC framework written in PHP 5. Its structure is designed to get the best of the MVC pattern, but with great ease of use. Thanks to its versatility and configurability, symfony is suitable for all web application projects. 
    713 Now that you understand the underlying theory behind symfony, you are almost ready to develop your first application. But before that, you need a symfony installation up and running on your development server.