Development

Documentation/ja_JP/book/1.0/05-Configuring-Symfony-1 (diff)

You must first sign up to be able to contribute.

Changes from Version 1 of Documentation/ja_JP/book/1.0/05-Configuring-Symfony-1

Show
Ignore:
Author:
heihachiro (IP: 125.100.73.82)
Timestamp:
02/08/07 12:46:37 (11 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Documentation/ja_JP/book/1.0/05-Configuring-Symfony-1

    v0 v1  
     1 
     2{{{ 
     3Chapter 5 - Configuring Symfony 
     4=============================== 
     5 
     6To be simple and easy to use, symfony defines a few conventions, which should satisfy the most common requirements of standard applications without need for modification. However, using a set of simple and powerful configuration files, it is possible to customize almost everything about the way the framework and your application interact with each other. With these files, you will also be able to add specific parameters for your applications. 
     7 
     8This chapter explains how the configuration system works: 
     9 
     10  * The symfony configuration is kept in files written in YAML, although you can always choose another format. 
     11  * Configuration files are at the project, application, and module levels in a project's directory structure. 
     12  * You can define several sets of configuration settings; in symfony, a set of configuration is called an environment. 
     13  * The values defined in the configuration files are available from the PHP code of your application. 
     14  * Additionally, symfony authorizes PHP code in YAML files and other tricks to make the configuration system even more flexible. 
     15 
     16The Configuration System 
     17------------------------ 
     18 
     19Regardless of purpose, most web applications share a common set of characteristics. For instance, some sections can be restricted to a subset of users, or the pages can be decorated by a layout, or a form can be filled with the user input after a failed validation. A framework defines a structure for emulating these characteristics, and the developer can further tweak them by changing a configuration setting. This strategy saves a lot of development time, since many changes don't require a single line of code, even if there is a lot of code behind. It is also much more efficient, because it ensures such information can be maintained in a single and easily identifiable location. 
     20 
     21However, this approach has two serious drawbacks: 
     22 
     23  * Developers end up writing endlessly complex XML files. 
     24  * In a PHP architecture, every request takes much longer to process. 
     25 
     26Taking these disadvantages into account, symfony uses configuration files only for what they are best at doing. As a matter of fact, the ambition of the configuration system in symfony is to be: 
     27 
     28  * Powerful: Almost every aspect that can be managed using configuration files is managed using configuration files. 
     29  * Simple: Many aspects of configuration are not shown in a normal application, since they seldom need to be changed. 
     30  * Easy: Configuration files are easy to read, to modify, and to create by the developer. 
     31  * Customizable: The default configuration language is YAML, but it can be INI, XML, or whatever format the developer prefers. 
     32  * Fast: The configuration files are never processed by the application but by the configuration system, which compiles them into a fast-processing chunk of code for the PHP server. 
     33 
     34### YAML Syntax and Symfony Conventions 
     35 
     36For its configuration, symfony uses the YAML format by default, instead of more traditional INI or XML formats. YAML shows structure through indentation and is fast to write. Its advantages and basic rules were already described in Chapter 1. However, you need to keep a few conventions in mind when writing YAML files. This section introduces several of the most prominent conventions. For a complete dissertation on the topic, visit the YAML website ((`http://www. yaml.org/`). 
     37 
     38First of all, never use tabs in YAML files; use spaces instead. YAML parsers can't understand files with tabs, so indent your lines with spaces (a double blank is the symfony convention for indentation), as shown in Listing 5-1. 
     39 
     40Listing 5-1 - YAML Files Forbid Tabs 
     41 
     42    # Never use tabs 
     43    all: 
     44    -> mail: 
     45    -> -> webmaster:  webmaster@example.com 
     46 
     47    # Use blanks instead 
     48    all: 
     49      mail: 
     50        webmaster: webmaster@example.com 
     51 
     52If your parameters are strings starting or ending with spaces, enclose the value in single quotes. If a string parameter contains special characters, also enclose the value in single quotes, as shown in Listing 5-2. 
     53 
     54Listing 5-2 - Nonstandard Strings Should Be Enclosed in Single Quotes 
     55 
     56    error1: This field is compulsory 
     57    error2: '  This field is compulsory  ' 
     58    error3: 'Don''t leave this field blank'   # Single quotes must be doubled 
     59 
     60You can define long strings in multiple lines, and also multiple-line strings, with the special string headers (> and |) plus an additional indentation. Listing 5-3 demonstrates this convention. 
     61 
     62Listing 5-3 - Defining Long and Multiline Strings 
     63 
     64    accomplishment: >           # Folded style, introduced by > 
     65      Mark set a major league   # Each line break is folded to a space 
     66      home run record in 1998.  # Makes YAML more readable 
     67    stats: |                    # Literal style, introduced by | 
     68      65 Home Runs              # All line breaks count 
     69      0.278 Batting Average     # Indentation doesn't appear in the resulting string 
     70 
     71To define a value as an array, enclose the elements in square brackets or use the expanded syntax with dashes, as shown in Listing 5-4. 
     72 
     73Listing 5-4 - YAML Array Syntax 
     74 
     75    # Shorthand syntax for arrays 
     76    players: [ Mark McGwire, Sammy Sosa, Ken Griffey ] 
     77 
     78    # Expanded syntax for arrays 
     79    players: 
     80      - Mark McGwire 
     81      - Sammy Sosa 
     82      - Ken Griffey 
     83 
     84To define a value as an associative array, or hash, enclose the elements in curly brackets and always insert a space between the key and the value in the `key: value` couple. You can also use the expanded syntax by adding indentation and a carriage return for every new key, as shown in Listing 5-5. 
     85 
     86Listing 5-5 - YAML Associative Array Syntax 
     87 
     88    # Incorrect syntax, blanks are missing after the colon 
     89    mail: {webmaster:webmaster@example.com,contact:contact@example.com} 
     90 
     91    # Correct shorthand syntax for associative arrays 
     92    mail: { webmaster: webmaster@example.com, contact: contact@example.com } 
     93 
     94    # Expanded syntax for associative arrays 
     95    mail: 
     96      webmaster: webmaster@example.com 
     97      contact:   contact@example.com 
     98 
     99To give a Boolean value, use either `on`, `1`, or `true` for a positive value and `off`, `0`, or `false` for a negative one. Listing 5-6 shows the possible Boolean values. 
     100 
     101Listing 5-6 - YAML Boolean Values Syntax 
     102 
     103    true_values:   [ on, 1, true ] 
     104    false_values:  [ off, 0, false ] 
     105 
     106Don't hesitate to add comments (starting with the hash mark, `#`) and extra spaces to values to make your YAML files more readable, as shown in Listing 5-7. 
     107 
     108Listing 5-7 - YAML Comments Syntax and Value Alignment 
     109 
     110    # This is a comment line 
     111    mail: 
     112      webmaster: webmaster@example.com 
     113      contact:   contact@example.com 
     114      admin:     admin@example.com   # extra spaces allow nice alignment of values 
     115 
     116In some symfony configuration files, you will sometimes see lines that start with a hash mark (and, as such, ignored by the YAML parsers) but look like usual settings lines. This is a symfony convention: the default configuration, inherited from other YAML files located in the symfony core, is repeated in commented lines in your application configuration, for your information. If you want to change the value of such a parameter, you need to uncomment the line first, as shown in Listing 5-8. 
     117 
     118Listing 5-8 - Default Configuration Is Shown Commented 
     119 
     120    # The cache is off by default 
     121    settings: 
     122    # cache: off 
     123 
     124    # If you want to change this setting, uncomment the line first 
     125    settings: 
     126      cache: on 
     127 
     128Symfony sometimes groups the parameter definitions into categories. All settings of a given category appear indented under the category header. Structuring long lists of `key: value` pairs by grouping them into categories improves the readability of the configuration. Category headers start with a dot (`.`). Listing 5-9 shows an example of categories. 
     129 
     130Listing 5-9 - Category Headers Look Like Keys, But Start with a Dot 
     131 
     132    all: 
     133      .general: 
     134        tax:        19.6 
     135 
     136      mail: 
     137        webmaster:  webmaster@example.com 
     138 
     139In this example, `mail` is a key and `general` is only a category header. Everything works as if the category header didn't exist, as shown in Listing 5-10. The `tax` parameter is actually a direct child of the `all` key. 
     140 
     141Listing 5-10 - Category Headers Are Only There for Readability and Are Actually Ignored 
     142 
     143    all: 
     144      tax:          19.6 
     145 
     146      mail: 
     147        webmaster:  webmaster@example.com 
     148 
     149>**SIDEBAR** 
     150>And if you don't like YAML 
     151> 
     152>YAML is just an interface to define settings to be used by PHP code, so the configuration defined in YAML files ends up being transformed into PHP. After browsing an application, check its cached configuration (in `cache/myapp/dev/config/`, for instance). You will see the PHP files corresponding to your YAML configuration. You will learn more about the configuration cache later in this chapter. 
     153> 
     154>The good news is that if you don't want to use YAML files, you can still do what the configuration files do by hand, in PHP or via another format (XML, INT, and so on). Throughout this book, you will meet alternative ways to define configuration without YAML, and you will even learn to replace the symfony configuration handlers (in Chapter 19). If you use them wisely, these tricks will enable you to bypass configuration files or define your own configuration format. 
     155 
     156### Help, a YAML File Killed My App! 
     157 
     158The YAML files are parsed into PHP hashes and arrays, and then the values are used in various parts of the application to modify the behavior of the view, the controller, or the model. Many times, when there is a problem in a YAML file, it is not detected until the value actually needs to be used. Moreover, the error or exception that is thrown then is usually not clearly related to the YAML configuration file. 
     159 
     160If your application suddenly stops working after a configuration change, you should check that you didn't make any of the common mistakes of the inattentive YAML coder: 
     161 
     162  * You miss a space between a key and its value: 
     163 
     164    key1:value1      # A space is missing after the : 
     165 
     166  * Keys in a sequence are not indented the same way: 
     167 
     168    all: 
     169      key1:  value1 
     170       key2: value2  # Indentation is not the same as the other sequence members 
     171      key3:  value3 
     172 
     173  * There is a reserved YAML character in a key or a value, without string delimiters: 
     174 
     175    message: tell him: go way    # :, [, ], { and } are reserved in YAML 
     176    message: 'tell him: go way'  # Correct syntax 
     177 
     178  * You are modifying a commented line: 
     179 
     180    # key: value     # Will never be taken into account due to the leading # 
     181 
     182  * You set values with the same key name twice at the same level: 
     183 
     184    key1: value1 
     185    key2: value2 
     186    key1: value3     # key1 is defined twice, the value is the last one defined 
     187 
     188  * You think that the setting takes a special type, while it is always a string, until you convert it: 
     189 
     190    income: 12,345   # Until you convert it, this is still a string 
     191 
     192Overview of the Configuration Files 
     193----------------------------------- 
     194 
     195Configuration is distributed into files, by subject. The files contain parameter definitions, or settings. Some of these parameters can be overridden at several levels (project, application, and module); some are specific to a certain level. The next chapters will deal with the configuration files related to their main topic, and Chapter 19 will deal with advanced configuration. 
     196 
     197### Project Configuration 
     198 
     199There are a few project configuration files by default. Here are the files that can be found in the `myproject/config/` directory: 
     200 
     201  * `config.php`: This is the very first file executed by any request or command. It contains the path to the framework files, and you can change it to use a different installation. If you add some `define` statements at the end of this file, the constants will be accessible from every application of the project. See Chapter 19 for advanced usage of this file. 
     202  * `databases.yml`: This is where you define the access and connection settings to the database (host, login, password, database name, and so on). Chapter 8 will tell you more about it. It can also be overridden at the application level. 
     203  * `properties.ini`: This file holds a few parameters used by the command line tool, including the project name and the connection settings for distant servers. See Chapter 16 for an overview of the features using this file. 
     204  * `rs`ync_exclude.txt: This file specifies which directories must be excluded from the synchronization between servers. It is discussed in Chapter 16. 
     205  * `schema.yml` and `propel.ini`: These are data access configuration files used by Propel (symfony's ORM layer). They are used to make the Propel libraries work with the symfony classes and the data of your project. `schema.yml` contains a representation of the project's relational data model. `propel.ini` is automatically generated, so you probably do not need to modify it. If you don't use Propel, these files are not needed. Chapter 8 will tell you more about their use. 
     206 
     207These files are mostly used by external components or by the command line, or they need to be processed even before any YAML parsing program can be loaded by the framework. That's why some of them don't use the YAML format. 
     208 
     209### Application Configuration 
     210 
     211The main part of the configuration is the application configuration. It is defined in the front controller (in the web/ directory) for the main constants, in YAML files located in the application config/ directory, in i18n/ directories for the internationalization files, and in the framework files for invisible--although useful--additional application configuration. 
     212 
     213#### Front Controller Configuration 
     214 
     215The very first application configuration is actually found in the front controller; that is the very first script executed by a request. Take a look at the default `web/index.php` in Listing 5-11. 
     216 
     217Listing 5-11 - The Default Production Front Controller 
     218 
     219    [php] 
     220    <?php 
     221 
     222    define('SF_ROOT_DIR',    dirname(__FILE__).'/..'); 
     223    define('SF_APP',         'myapp'); 
     224    define('SF_ENVIRONMENT', 'prod'); 
     225    define('SF_DEBUG',       true); 
     226 
     227    require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php'); 
     228 
     229    sfContext::getInstance()->getController()->dispatch(); 
     230 
     231After defining the name of the application (`myapp`) and the environment (`prod`), the general configuration file is called before the dispatching. So a few useful constants are defined here: 
     232 
     233  * `SF_ROOT_DIR`: Project root directory (normally, should remain at its default value, unless you change the file structure). 
     234  * `SF_APP`: Application name in the project. Necessary to compute file paths. 
     235  * `SF_ENVIRONMENT`: Environment name (`prod`, `dev`, or any other project-specific environment that you define). Will determine which configuration settings are to be used. Environments are explained later in this chapter. 
     236  * `SF_DEBUG`: Activation of the debug mode (see Chapter 16 for details). 
     237 
     238If you want to change one of these values, you probably need an additional front controller. The next chapter will tell you more about front controllers and how to create a new one. 
     239 
     240>**SIDEBAR** 
     241>The root directory can be anywhere 
     242> 
     243>Only the files and scripts located under the web root (the `web/` directory in a symfony project) are available from the outside. The front controller scripts, images, style sheets, and JavaScript files are public. All the other files must be outside the server web root--that means they can be anywhere else. 
     244> 
     245>The non-public files of a project are accessed by the front controller from the SF_ROOT_DIR path. Classically, the root directory is one level up the `web/` directory. But you can choose a completely different structure. Imagine that your main directory structure is made of two directories, one public and one private: 
     246> 
     247> 
     248>    symfony/    # Private area 
     249>      apps/ 
     250>      batch/ 
     251>      cache/ 
     252>      ... 
     253>    www/        # Public area 
     254>      images/ 
     255>      css/ 
     256>      js/ 
     257>      index.php 
     258> 
     259> 
     260>In this case, the root directory is the `symfony/` directory. So the `index.php` front controller simply needs to define the `SF_ROOT_DIR` as follows for the application to work: 
     261> 
     262>    define('SF_ROOT_DIR', dirname(__FILE__).'/../symfony'); 
     263 
     264Chapter 19 will give you more information about how to tweak symfony to make it work on a specific directory structure. 
     265 
     266#### Main Application Configuration 
     267 
     268The main application configuration is stored in files located in the `myproject/apps/myapp/config/` directory: 
     269 
     270  * `app.yml`: This file should contain the application-specific configuration; that is, global variables defining business or applicative logic specific to an application, which don't need to be stored in a database. Tax rates, shipping fares, and e-mail addresses are often stored in this file. It is empty by default. 
     271  * `config.php`: This file bootstraps the application, which means that it does all the very basic initializations to allow the application to start. This is where you can customize your directory structure or add application-specific constants (Chapter 19 provides more details). It starts by including the project's `config.php`. 
     272  * `fact`ories.yml: Symfony defines its own class to handle the view, the request, the response, the session, and so on. If you want to use your own classes instead, this is where you can specify them. Chapter 19 provides more information. 
     273  * `filters.yml`: Filters are portions of code executed for every request. This file is where you define which filters are to be processed, and it can be overridden for each module. Chapter 6 discusses filters in more detail. 
     274  * `logging.yml`: This file defines which level of detail must be recorded in the logs, to help you manage and debug your application. The use of this configuration is explained in Chapter 16. 
     275  * `routing.yml`: The routing rules, which allow transforming unreadable and unbookmarkable URLs into "smart" and explicit ones, are stored in this file. For new applications, a few default rules exist. Chapter 9 is all about links and routing. 
     276  * `settings.yml`: The main settings of a symfony application are defined in this file. This is where you specify if your application has internationalization, its default language, the request timeout and whether caching is turned on. With a one-line change in this file, you can shut down the application so you can perform maintenance or upgrade one of its components. The common settings and their use are described in Chapter 19. 
     277  * `view.yml`: The structure of the default view (name of the layout, title, and meta tags; default style sheets and JavaScript files to be included; default content-type, and so on) is set in this file. It also defines the default value of the meta and title tags. Chapter 7 will tell you more about this file. These settings can be overridden for each module. 
     278 
     279#### Internationalization Configuration 
     280 
     281Internationalized applications can display pages in several languages. This requires specific configuration. There are two configuration places for internationalization: 
     282 
     283  * `i18n.yml` of the application `config/` directory: This file defines general translation settings, such as the default culture for the translation, whether the translations come from files or a database, and their format. 
     284  * Translation files in the application `i18n/` directory: These are basically dictionaries, giving a translation for each of the phrases used in the application templates so that the pages show translated text when the user switches language. 
     285 
     286Note that the activation of the i18n features is set in the `settings.yml` file. You will find more information about these features in Chapter 13. 
     287 
     288#### Additional Application Configuration 
     289 
     290A second set of configuration files is in the symfony installation directory (in `$sf_symfony_ data_dir/config/`) and doesn't appear in the configuration directory of your applications. The settings defined there are defaults that seldom need to be modified, or that are global to all projects. However, if you need to modify them, just create an empty file with the same name in your `myproject/apps/myapp/config/` directory, and override the settings you want to change. The settings defined in an application always have precedence over the ones defined in the framework. The following are the configuration files in the symfony installation config/ directory: 
     291 
     292  * `autoload.yml`: This file contains the settings of the autoloading feature. This feature exempts you from requiring custom classes in your code if they are located in specific directories. It is described in detail in Chapter 19. 
     293  * `constants.php`: This file contains the default application file structure. To override the settings of this file, use the application `config.php`, as explained in Chapter 19. 
     294  * `c`ore_compile.yml and bootstrap_compile.yml: These are lists of classes to be included to start an application (in bootstrap_compile.yml) and to process a request (in core_compile.yml). These classes are actually concatenated into an optimized PHP file without comments, which will accelerate the execution by minimizing the file access operations (one file is loaded instead of more than forty for each request). This is especially useful if you don't use a PHP accelerator. Optimization techniques are described in Chapter 18. 
     295  * `config_handlers.yml`: This is where you can add or modify the handlers used to process each configuration file. Chapter 19 provides more details. 
     296  * `php.yml`: This file checks that the variables of the `php.ini` file are properly defined and allows you to override them, if necessary. Check Chapter 19 for details. 
     297 
     298### Module Configuration 
     299 
     300By default, a module has no specific configuration. But, if required, you can override some application-level settings for a given module. For instance, you might do this to change the HTML description of all the actions of a module, or to include a specific JavaScript file. You can also choose to add new parameters restricted to a specific module to preserve encapsulation. 
     301 
     302As you may have guessed, module configuration files must be located in a `myproject/apps/myapp/modules/mymodule/config/` directory. These files are as follows: 
     303 
     304  * `generator.yml`: For modules generated according to a database table (scaffoldings and administrations), this file defines how the interface displays rows and fields, and which interactions are proposed to the user (filters, sorting, buttons, and so on). Chapter 14 will tell you more about it. 
     305  * `module.yml`: This file contains custom parameters specific to a module (equivalent to the `app.`yml, but at the module level) and action configuration. Chapter 6 provides more details. 
     306  * `security.yml`: This file sets access restrictions for actions. This is where you specify that a page can be viewed only by registered users or by a subset of registered users with special permissions. Chapter 6 will tell you more about it. 
     307  * `view.yml`: This file contains configuration for the views of one or all of the actions of a module. It overrides the application `view.yml` and is described in Chapter 7. 
     308  * Data validation files: Although located in the `validate/` directory instead of the `config/` one, the YAML data validation files, used to control the data entered in forms, are also module configuration files. You will learn how to use them in Chapter 10. 
     309 
     310Most module configuration files offer the ability to define parameters for all the views or all the actions of a module, or for a subset of them. 
     311 
     312>**SIDEBAR** 
     313>**Too many files? 
     314> 
     315>You might be overwhelmed by the number of configuration files present in the application. But please keep the following in mind: 
     316> 
     317>Most of the time, you don't need to change the configuration, since the default conventions match the most common requirements. Each configuration file is related to a particular feature, and the next chapters will detail their use one by one. When you focus on a single file, you can see clearly what it does and how it is organized. For professional web development, the default configuration is often not completely adapted. The configuration files allow for an easy modification of the symfony mechanisms without code. Imagine the amount of PHP code necessary to achieve the same amount of control. If all the configuration were located in one file, not only would the file be completely unreadable, but you could not redefine configuration at several levels (see the "Configuration Cascade" section later in this chapter). 
     318> 
     319>The configuration system is one of the great strengths of symfony, because it makes symfony usable for almost every kind of web application, and not only for the ones for which the framework was originally designed. 
     320 
     321Environments 
     322------------ 
     323 
     324During the course of application development, you will probably need to keep several sets of configuration in parallel. For instance, you will need to have the connection settings for your tests database available during development, and the ones for your real data available for production. To answer the need of concurrent configurations, symfony offers different environments. 
     325 
     326### What Is an Environment? 
     327 
     328An application can run in various environments. The different environments share the same PHP code (apart from the front controller), but can have completely different configurations. For each application, symfony provides three default environments: production (`prod`), test (test), and development (dev). You're also free to add as many custom environments as you wish. 
     329 
     330So basically, environments and configuration are synonyms. For instance, a test environment will log alerts and errors, while a `prod` environment will only log errors. Cache acceleration is often deactivated in the `dev` environment, but activated in the `test` and `prod` environments. The `dev` and `test` environments may need test data, stored in a database distinct from the one used in the production environment. So the database configuration will be different between the two environments. All environments can live together on the same machine, although a production server generally contains only the `prod` environment. 
     331 
     332In the `dev` environment, the logging and debugging settings are all enabled, since maintenance is more important than performance. On the contrary, the prod environment has settings optimized for performance by default, so the production configuration turns off many features. A good rule of thumb is to navigate in the development environment until you are satisfied with the feature you are working on, and then switch to the production environment to check its speed. 
     333 
     334The test environment differs from the dev and prod environment in other ways. You interact with this environment solely through the command line for the purpose of functional testing and batch scripting. Consequently, the test environment is close to the production one, but it is not accessed through a web browser. It simulates the use of cookies and other HTTP specific components. 
     335 
     336To change the environment in which you're browsing your application, just change the front controller. Until now, you have seen only the development environment, since the URLs used in the example called the development front controller: 
     337 
     338    http://localhost/myapp_dev.php/mymodule/index 
     339 
     340However, if you want to see how the application reacts in production, call the production front controller instead: 
     341 
     342    http://localhost/index.php/mymodule/index 
     343 
     344If your web server has mod_rewrite enabled, you can even use the custom symfony rewriting rules, written in `web/.htaccess`. They define the production front controller as the default execution script and allow for URLs like this: 
     345 
     346    http://localhost/mymodule/index 
     347 
     348>**SIDEBAR** 
     349>Environments and servers 
     350> 
     351>Don't mix up the notions of environment and server. In symfony, different environments are different configurations, and correspond to a front controller (the script that executes the request). Different servers correspond to different domain names in the URL. 
     352> 
     353> 
     354>    http://localhost/myapp_dev.php/mymodule/index 
     355>           _________ _____________ 
     356>            server    environment 
     357> 
     358> 
     359>Usually, developers work on applications in a development server, disconnected from the Internet and where all the server and PHP configuration can be changed at will. When the time comes for releasing the application to production, the application files are transferred to the production server and made accessible to the end users. 
     360> 
     361>This means that many environments are available on each server. For instance, you can run in the production environment even on your development server. However, most of the time, only the production environment should be accessible in the production server, to avoid public visibility of server configuration and security risks. 
     362> 
     363>To add a new environment, you don't need to create a directory or to use the symfony CLI. Simply create a new front controller and change the environment name definition in it. This environment inherits all the default configuration plus the settings that are common to all environments. The next chapter will show you how to do this. 
     364 
     365### Configuration Cascade 
     366 
     367The same setting can be defined more than once, in different places. For instance, you may want to set the mime-type of your pages to `text/html` for all of the application, except for the pages of an `rss` module, which will need a `text/xml` mime-type. Symfony gives you the ability to write the first setting in `myapp/config/view.yml` and the second in `myapp/modules/rss/config/view.yml`. The configuration system knows that a setting defined at the module level must override a setting defined at the application level. 
     368 
     369In fact, there are several configuration levels in symfony: 
     370 
     371  * Granularity levels: 
     372    * The default configuration located in the framework 
     373    * The global configuration for the whole project (in `myproject/config/`) 
     374    * The local configuration for an application of the project (in `myproject/apps/myapp/config/`) 
     375    * The local configuration restricted to a module (in `myproject/apps/myapp/modules/mymodule/config/`) 
     376  * Environment levels: 
     377    * Specific to one environment 
     378    * For all environments 
     379 
     380Of all the properties that can be customized, many are environment-dependent. Consequently, many YAML configuration files are divided by environment, plus a tail section for all environments. The result is that typical symfony configuration looks like Listing 5-12. 
     381 
     382Listing 5-12 - The Structure of Symfony Configuration Files 
     383 
     384    # Production environment settings 
     385    prod: 
     386      ... 
     387 
     388    # Development environment settings 
     389    dev: 
     390      ... 
     391 
     392    # Test environment settings 
     393    test: 
     394      ... 
     395 
     396    # Custom environment settings 
     397    myenv: 
     398      ... 
     399 
     400    # Settings for all environments 
     401    all: 
     402      ... 
     403 
     404In addition, the framework itself defines default values in files that are not located in the project tree structure, but in the $sf_symfony_data_dir/config/ directory of your symfony installation. The default configuration is set in these files as shown in Listing 5-13. These settings are inherited by all applications. 
     405 
     406Listing 5-13 - The Default Configuration, in `$sf_symfony_data_dir/config/settings.yml` 
     407 
     408     # Default settings: 
     409     default: 
     410       default_module:         default 
     411       default_action:         index 
     412       ... 
     413 
     414These default definitions are repeated in the project, application, and module configuration files as comments, as shown in Listing 5-14, so that you know that some parameters are defined by default and that they can be modified. 
     415 
     416Listing 5-14 - The Default Configuration, Repeated for Information, in `myapp/config/settings.yml` 
     417 
     418    #all: 
     419     #  default_module:         default 
     420     #  default_action:         index 
     421     ... 
     422 
     423This means that a property can be defined several times, and the actual value results from a definition cascade. A parameter definition in a named environment has precedence over the same parameter definition for all environments, which has precedence over a definition in the default configuration. A parameter definition at the module level has precedence over the same parameter definition at the application level, which has precedence over a definition at the project level. This can be wrapped up in the following priority list: 
     424 
     425  1. Module 
     426  2. Application 
     427  3. Project 
     428  4. Specific environment 
     429  5. All environments 
     430  6. Default 
     431 
     432The Configuration Cache 
     433----------------------- 
     434 
     435Parsing YAML and dealing with the configuration cascade at runtime represent a significant overhead for each request. Symfony has a built-in configuration cache mechanism designed to speed up requests. 
     436 
     437The configuration files, whatever their format, are processed by some special classes, called handlers, that transform them into fast-processing PHP code. In the development environment, the handlers check the configuration for changes at each request, to promote interactivity. They parse the recently modified files so that you can see a change in a YAML file immediately. But in the production environment, the processing occurs once during the first request, and then the processed PHP code is stored in the cache for subsequent requests. The performance is guaranteed, since every request in production will just execute some well-optimized PHP code. 
     438 
     439For instance, if the `app.yml` file contains this: 
     440 
     441    all:                   # Setting for all environments 
     442      mail: 
     443        webmaster:         webmaster@example.com 
     444 
     445then the file `config_app.yml.php`, located in the `cache/` folder of your project, will contain this: 
     446 
     447    [php] 
     448    <?php 
     449 
     450    sfConfig::add(array( 
     451      'app_mail_webmaster' => 'webmaster@example.com', 
     452    )); 
     453 
     454As a consequence, most of the time, the YAML files aren't even parsed by the framework, which relies on the configuration cache instead. However, in the development environment, symfony will systematically compare the dates of modification of the YAML files and the cached files, and reprocess only the ones that have changed since the previous request. 
     455 
     456This presents a major advantage over many PHP frameworks, where configuration files are compiled at every request, even in production. Unlike Java, PHP doesn't share an execution context between requests. For other PHP frameworks, keeping the flexibility of XML configuration files requires a major performance hit to process all the configuration at every request. This is not the case in symfony. Thanks to the cache system, the overhead caused by configuration is very low. 
     457 
     458There is an important consequence of this mechanism. If you change the configuration in the production environment, you need to force the reparsing of all the configuration files for your modification to be taken into account. For that, you just need to clear the cache, either by deleting the content of the cache/ directory or, more easily, by calling the clear-cache symfony task: 
     459 
     460    > symfony clear-cache 
     461 
     462Accessing the Configuration from Code 
     463------------------------------------- 
     464 
     465All the configuration files are eventually transformed into PHP, and many of the settings they contain are automatically used by the framework, without further intervention. However, you sometimes need to access some of the settings defined in the configuration files from your code (in actions, templates, custom classes, and so on). The settings defined in settings.yml, app.yml, module.yml, logging.yml, and i18n.yml are available through a special class called sfConfig. 
     466 
     467### The sfConfig Class 
     468 
     469You can access settings from within the application code through the `sfConfig` class. It is a registry for configuration parameters, with a simple getter class method, accessible from every part of the code: 
     470 
     471    [php] 
     472    // Retrieve a setting 
     473    parameter = sfConfig::get('param_name', $default_value); 
     474 
     475Note that you can also define, or override, a setting from within PHP code: 
     476 
     477    [php] 
     478    // Define a setting 
     479    sfConfig::set('param_name', $value); 
     480 
     481The parameter name is the concatenation of several elements, separated by underscores, in this order: 
     482 
     483  * A prefix related to the configuration file name (`sf_` for `settings.yml`, `app_` for `app.yml`, `mod_` for `module.yml`, `sf_i18n_` for `i18n.yml`, and `sf_logging_` for `logging.yml`) 
     484  * The parent keys (if defined), in lowercase 
     485  * The name of the key, in lowercase 
     486 
     487The environment is not included, since your PHP code will have access only to the values defined for the environment in which it's executed. 
     488 
     489For instance, if you need to access the values defined in the app.yml file shown in Listing 5-15, you will need the code shown in Listing 5-16. 
     490 
     491Listing 5-15 - Sample `app.yml` Configuration 
     492 
     493    all: 
     494      version:        1.5 
     495      .general: 
     496        tax:          19.6 
     497      default_user: 
     498        name:         John Doe 
     499      mail: 
     500        webmaster:    webmaster@example.com 
     501        contact:      contact@example.com 
     502    dev: 
     503      mail: 
     504        webmaster:    dummy@example.com 
     505        contact:      dummy@example.com 
     506 
     507Listing 5-16 - Accessing Configuration Settings in PHP in the `dev` Environment 
     508 
     509    [php] 
     510    echo sfConfig::get('app_version'); 
     511     => '1.5' 
     512    echo sfConfig::get('app_tax');   // Remember that category headers are ignored 
     513     => '19.6' 
     514    echo sfConfig::get('app_default_user_name); 
     515     => 'John Doe' 
     516    echo sfConfig::get('app_mail_webmaster'); 
     517     => 'dummy@example.com' 
     518    echo sfConfig::get('app_mail_contact'); 
     519     => 'dummy@example.com' 
     520 
     521So symfony configuration settings have all the advantages of PHP constants, but without the disadvantages, since the value can be changed. 
     522 
     523On that account, the `settings.yml` file, where you can set the framework settings for an application, is the equivalent to a list of `sfConfig::set()` calls. Listing 5-17 is interpreted as shown in Listing 5-18. 
     524 
     525Listing 5-17 - Extract of `settings.yml` 
     526 
     527    all: 
     528      .settings: 
     529        available:              on 
     530        path_info_array:        SERVER 
     531        path_info_key:          PATH_INFO 
     532        url_format:             PATH 
     533 
     534Listing 5-18 - What Symfony Does When Parsing `settings.yml` 
     535 
     536    [php] 
     537    sfConfig::add(array( 
     538      'sf_available' => true, 
     539      'sf_path_info_array' => 'SERVER', 
     540      'sf_path_info_key' => 'PATH_INFO', 
     541      'sf_url_format' => 'PATH', 
     542    )); 
     543 
     544Refer to Chapter 19 for the meanings of the settings found in the `settings.yml` file. 
     545 
     546### Custom Application Settings and app.yml 
     547 
     548Most of the settings related to the features of an application should be stored in the `app.yml` file, located in the `myproject/apps/myapp/config/` directory. This file is environment-dependent and empty by default. Put in every setting that you want to be easily changed, and use the `sfConfig` class to access these settings from your code. Listing 5-19 shows an example. 
     549 
     550Listing 5-19 - Sample `app.yml` to Define Credit Card Operators Accepted for a Given Site 
     551 
     552    all: 
     553      creditcards: 
     554        fake:             off 
     555        visa:             on 
     556        americanexpress:  on 
     557 
     558    dev: 
     559      creditcards: 
     560        fake:             on 
     561 
     562To know if the `fake` credit cards are accepted in the current environment, get the value of: 
     563 
     564    [php] 
     565    sfConfig::get('app_creditcards_fake'); 
     566 
     567>**TIP** 
     568>Each time you are tempted to define a constant or a setting in one of your scripts, think about if it would be better located in the app.yml file. This is a very convenient place to store all application settings. 
     569 
     570When your need for custom parameters becomes hard to handle with the `app.yml` syntax, you may need to define a syntax of your own. In that case, you can store the configuration in a new file, interpreted by a new configuration handler. Refer to Chapter 19 for more information about configuration handlers. 
     571 
     572Tips for Getting More from Configuration Files 
     573---------------------------------------------- 
     574 
     575There are a few last tricks to learn before writing your own YAML files. They will allow you to avoid configuration duplication and to deal with your own YAML formats. 
     576 
     577### Using Constants in YAML Configuration Files 
     578 
     579Some configuration settings rely on the value of other settings. To avoid setting the same value twice, symfony supports constants in YAML files. On encountering a setting name (one that can be accessed by sfConfig::get()) in capital letters enclosed in % signs, the configuration handlers replace them with their current value. See Listing 5-20 for an example. 
     580 
     581Listing 5-20 - Using Constants in YAML Files, Example from `autoload.yml` 
     582 
     583    autoload: 
     584      symfony: 
     585        name:           symfony 
     586        path:           %SF_SYMFONY_LIB_DIR% 
     587        recursive:      on 
     588        exclude:        [vendor] 
     589 
     590The path parameter will take the value returned by sfConfig::get('sf_symfony_lib_dir'). If you want one configuration file to rely on another, you need to make sure that the file you rely on is already parsed (look in the symfony source to find out the order in which the configuration files are parsed). `app.yml` is one of the last files parsed, so you may rely on others in it. 
     591 
     592### Using Scriptable Configuration 
     593 
     594It may happen that your configuration relies on external parameters (such as a database or another configuration file). To deal with these particular cases, the symfony configuration files are parsed as PHP files before being passed to the YAML parser. It means that you can put PHP code in YAML files, as in Listing 5-21. 
     595 
     596Listing 5-21 - YAML Files Can Contain PHP 
     597 
     598    all: 
     599      translation: 
     600        format:  <?php echo sfConfig::get('sf_i18n') == true ? 'xliff' : 'none' ?> 
     601 
     602But be aware that the configuration is parsed very early in the life of a request, so you will not have any symfony built-in methods or functions to help you. 
     603 
     604>**CAUTION** 
     605>In the production environment, the configuration is cached, so the configuration files are parsed (and executed) only once after the cache is cleared. 
     606 
     607### Browsing Your Own YAML File 
     608 
     609Whenever you want to read a YAML file directly, you can use the `sfYaml` class. It is a YAML parser that can turn a YAML file into a PHP associative array. Listing 5-22 presents a sample YAML file, and Listing 5-23 shows you how to parse it. 
     610 
     611Listing 5-22 - Sample `test.yml` File 
     612 
     613    house: 
     614      family: 
     615        name:     Doe 
     616        parents:  [John, Jane] 
     617        children: [Paul, Mark, Simone] 
     618      address: 
     619        number:   34 
     620        street:   Main Street 
     621        city:     Nowheretown 
     622        zipcode:  12345 
     623 
     624Listing 5-23 - Using the `sfYaml` Class to Turn a YAML File into an Associative Array 
     625 
     626    [php] 
     627    $test = sfYaml::load('/path/to/test.yml'); 
     628    print_r($test); 
     629 
     630    Array( 
     631      [house] => Array( 
     632        [family] => Array( 
     633          [name] => Doe 
     634          [parents] => Array( 
     635            [0] => John 
     636            [1] => Jane 
     637          ) 
     638          [children] => Array( 
     639            [0] => Paul 
     640            [1] => Mark 
     641            [2] => Simone 
     642          ) 
     643        ) 
     644        [address] => Array( 
     645          [number] => 34 
     646          [street] => Main Street 
     647          [city] => Nowheretown 
     648          [zipcode] => 12345 
     649        ) 
     650      ) 
     651    ) 
     652 
     653Summary 
     654------- 
     655 
     656The symfony configuration system uses the YAML language to be simple and readable. The ability to deal with multiple environments and to set parameters through a definition cascade offers versatility to the developer. Some of the configuration can be accessed from within the code via the `sfConfig` object, especially the application settings stored in the `app.yml` file. 
     657 
     658Yes, symfony does have a lot of configuration files, but this approach makes it more adaptable. Remember that you don't need to bother with them unless your application requires a high level of customization. 
     659 
     660}}}