19-Mastering-Symfony-s-Configuration-Files.txt 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. Chapter 19 - Mastering Symfony's Configuration Files
  2. ====================================================
  3. Now that you know symfony very well, you are already able to dig into its code to understand its core design and discover new hidden abilities. But before extending the symfony classes to match your own requirements, you should take a closer look at some of the configuration files. Many features are already built into symfony and can be activated by just changing configuration settings. This means that you can tweak the symfony core behavior without overriding its classes. This chapter takes you deep into the configuration files and their powerful capabilities.
  4. Symfony Settings
  5. ----------------
  6. The `frontend/config/settings.yml` file contains the main symfony configuration for the `frontend` application. You have already seen the function of many settings from this file in the previous chapters, but let's revisit them.
  7. As explained in Chapter 5, this file is environment-dependent, which means that each setting can take a different value for each environment. Remember that each parameter defined in this file is accessible from inside the PHP code via the `sfConfig` class. The parameter name is the setting name prefixed with `sf_`. For instance, if you want to get the value of the `cache` parameter, you just need to call `sfConfig::get('sf_cache')`.
  8. ### Default Modules and Actions
  9. Symfony provides default pages for special situations. In the case of a routing error, symfony executes an action of the `default` module, which is stored in the `$sf_symfony_lib_dir/controller/default/` directory. The `settings.yml` file defines which action is executed depending on the error:
  10. * `error_404_module` and `error_404_action`: Action called when the URL entered by the user doesn't match any route or when an `sfError404Exception` occurs. The default value is `default/error404`.
  11. * `login_module` and `login_action`: Action called when a nonauthenticated user tries to access a page defined as `secure` in `security.yml` (see Chapter 6 for details). The default value is `default/login`.
  12. * `secure_module` and `secure_action`: Action called when a user doesn't have the credentials required for an action. The default value is `default/secure`.
  13. * `module_disabled_module` and `module_disabled_action`: Action called when a user requests a module declared as disabled in `module.yml`. The default value is `default/disabled`.
  14. Before deploying an application to production, you should customize these actions, because the `default` module templates include the symfony logo on the page. See Figure 19-1 for a screenshot of one of these pages, the error 404 page.
  15. Figure 19-1 - Default 404 error page
  16. ![Default 404 error page](/images/book/F1901.jpg "Default 404 error page")
  17. You can override the default pages in two ways:
  18. * You can create your own default module in the application's `modules/` directory, override all the actions defined in the `settings.yml` file (`index`, `error404`, `login`, `secure`, `disabled`) and all the related templates (`indexSuccess.php`, `error404Success.php`, `loginSuccess.php`, `secureSuccess.php`, `disabledSuccess.php`).
  19. * You can change the default module and action settings of the `settings.yml` file to use pages of your application.
  20. Two other pages bear a symfony look and feel, and they also need to be customized before deployment to production. These pages are not in the `default` module, because they are called when symfony cannot run properly. Instead, you will find these default pages in the `$sf_symfony_lib_dir/exception/data/` directory:
  21. * `error500.php`: Page called when an internal server error occurs in the production environment. In other environments (where debug is set to `true`), when an error occurs, symfony displays the full execution stack and an explicit error message (see Chapter 16 for details).
  22. * `unavailable.php`: Page called when a user requests a page while the application is disabled (with the `disable` task). It is also called while the cache is being cleared (that is, between a call to the `php symfony cache:clear` task and the end of this task execution). On systems with a very large cache, the cache-clearing process can take several seconds. Symfony cannot execute a request with a partially cleared cache, so requests received before the end of the process are redirected to this page.
  23. To customize these pages, simply create `error500.php` and `unavailable.php` pages in your project or application's `web/errors/` directory. Symfony will use these instead of its own.
  24. >**NOTE**
  25. >To have requests redirected to the `unavailable.php` page when needed, you need to set the `check_lock` setting to `on` in the application `settings.yml`. The check is deactivated by default, because it adds a very slight overhead for every request.
  26. ### Optional Feature Activation
  27. Some parameters of the `settings.yml` file control optional framework features that can be enabled or disabled. Deactivating unused features boosts performances a bit, so make sure to review the settings listed in Table 19-1 before deploying your application.
  28. Table 19-1 - Optional Features Set Through `settings.yml`
  29. Parameter | Description | Default Value
  30. ----------------------- | ----------- | -------------
  31. `use_database` | Enables the database manager. Set it to `off` if you don't use a database. | `on`
  32. `i18n` | Enables interface translation (see Chapter 13). Set it to `on` for multilingual applications. | `off`
  33. `logging_enabled` | Enables logging of symfony events. Set it to off when you want to turn symfony logging off completely. | `on`
  34. `escaping_strategy` | Enables the output escaping feature (see Chapter 7). Set it to `on` if you want data passed to your templates to be escaped. | `off`
  35. `cache` | Enables template caching (see Chapter 12). Set it to `on` if one of your modules includes `cache.yml` file. The cache filter (`sfCacheFilter`) is enabled only if it is on. | `off` in development, `on` in production
  36. `web_debug` | Enables the web debug toolbar for easy debugging (see Chapter 16). Set it to `on` to display the toolbar on every page. | `on` in development, `off` in production
  37. `check_symfony_version` | Enables the check of the symfony version for every request. Set it to on for automatic cache clearing after a framework upgrade. Leave it set to off if you always clear the cache after an upgrade. | `off`
  38. `check_lock` | Enables the application lock system, triggered by the `cache:clear` and `project:disable` tasks (see the previous section). Set it to `on` to have all requests to disabled applications redirected to the `$sf_symfony_lib_dir/exception/data/unavailable.php` page. | `off`
  39. `compressed` | Enables PHP response compression. Set it to `on` to compress the outgoing HTML via the PHP compression handler. | `off`
  40. ### Feature Configuration
  41. Symfony uses some parameters of `settings.yml` to alter the behavior of built-in features such as form validation, cache, and third-party modules.
  42. #### Output Escaping Settings
  43. Output escaping settings control the way the variables are accessible in the template (see Chapter 7). The `settings.yml` file includes two settings for this feature:
  44. * The `escaping_strategy` setting can take the value `on`, or `off`.
  45. * The `escaping_method` setting can be set to `ESC_RAW`, `ESC_SPECIALCHARS`, `ESC_ENTITIES`, `ESC_JS`, or `ESC_JS_NO_ENTITIES`.
  46. #### Routing Settings
  47. The routing settings (see Chapter 9) are defined in `factories.yml`, under the `routing` key. Listing 19-1 show the default routing configuration.
  48. Listing 19-1 - Routing Configuration Settings, in `frontend/config/factories.yml`
  49. routing:
  50. class: sfPatternRouting
  51. param:
  52. load_configuration: true
  53. suffix: .
  54. default_module: default
  55. default_action: index
  56. variable_prefixes: [':']
  57. segment_separators: ['/', '.']
  58. variable_regex: '[\w\d_]+'
  59. debug: %SF_DEBUG%
  60. logging: %SF_LOGGING_ENABLED%
  61. cache:
  62. class: sfFileCache
  63. param:
  64. automatic_cleaning_factor: 0
  65. cache_dir: %SF_CONFIG_CACHE_DIR%/routing
  66. lifetime: 31556926
  67. prefix: %SF_APP_DIR%
  68. * The `suffix` parameter sets the default suffix for generated URLs. The default value is a period (`.`), and it corresponds to no suffix. Set it to `.html`, for instance, to have all generated URLs look like static pages.
  69. * When a routing rule doesn't define the `module` or the `action` parameter, values from the `factories.yml` are used instead:
  70. * `default_module`: Default `module` request parameter. Defaults to the `default` module.
  71. * `default_action`: Default `action` request parameter. Defaults to the `index` action.
  72. * By default, route patterns identify named wildcards by a colon (`:`) prefix. But if you want to write your rules in a more PHP-friendly syntax, you can add the dollar (`$`) sign in the `variable_prefixes` array. That way, you can write a pattern like '/article/$year/$month/$day/$title' instead of '/article/:year/:month/:day/:title'.
  73. * The pattern routing will identify named wildcards between separators. The default separators are the slash and the dot, but you can add more if you want in the `segment_separators` parameter. For instance, if you add the dash (`-`), you can write a pattern like '/article/:year-:month-:day/:title'.
  74. * The pattern routing uses its own cache, in production mode, to speed up conversions between external URLs and internal URIs. By default, this cache uses the filesystem, but you can use any cache class, provided that you declare the class and its settings in the `cache` parameter. See Chapter 15 for the list of available cache storage classes. To deactivate the routing cache in production, set the `debug` parameter to `on`.
  75. These are only the settings for the `sfPatternRouting` class. You can use another class for your application routing, either your own or one of symfony's routing factories (`sfNoRouting` and `sfPathInfoRouting`). With either of these two factories, all external URLs look like 'module/action?key1=param1'. No customization possible--but it's fast. The difference is that the first uses PHP's `GET`, and the second uses `PATH_INFO`. Use them mainly for backend interfaces.
  76. There is one additional parameter related to routing, but this one is stored in `settings.yml`:
  77. * `no_script_name` enables the front controller name in generated URLs. The `no_script_name` setting can be on only for a single application in a project, unless you store the front controllers in various directories and alter the default URL rewriting rules. It is usually on for the production environment of your main application and off for the others.
  78. #### Form Validation Settings
  79. >**NOTE**
  80. >The features described in this section are deprecated in symfony 1.1 and only work if you enable the `sfCompat10` plugin.
  81. Form validation settings control the way error messages output by the `Validation` helpers look (see Chapter 10). These errors are included in `<div>` tags, and they use the `validation_error_ class` setting as a `class` attribute and the `validation_error_id_prefix` setting to build up the `id` attribute. The default values are `form_error` and `error_for_`, so the attributes output by a call to the `form_error()` helper for an input named `foobar` will be `class="form_error" id="error_for_foobar"`.
  82. Two settings determine which characters precede and follow each error message: `validation_error_prefix` and `validation_error_suffix`. You can change them to customize all error messages at once.
  83. #### Cache Settings
  84. Cache settings are defined in `cache.yml` for the most part, except for two in `settings.yml`: `cache` enables the template cache mechanism, and `etag` enables ETag handling on the server side (see Chapter 15). You can also specify which storage to use for two all cache systems (the view cache, the routing cache, and the i18n cache) in `factories.yml`. Listing 19-2 show the default view cache factory configuration.
  85. Listing 19-2 - View Cache Configuration Settings, in `frontend/config/factories.yml`
  86. view_cache:
  87. class: sfFileCache
  88. param:
  89. automatic_cleaning_factor: 0
  90. cache_dir: %SF_TEMPLATE_CACHE_DIR%
  91. lifetime: 86400
  92. prefix: %SF_APP_DIR%/template
  93. The `class` can be any of `sfFileCache`, `sfAPCCache`, `sfEAcceleratorCache`, `sfXCacheCache`, `sfMemcacheCache`, and `sfSQLiteCache`. It can also be your own custom class, provided it extends `sfCache` and provides the same generic methods for setting, retrieving and deleting a key in the cache. The factory parameters depend on the class you choose, but there are constants:
  94. * `lifetime` defines the number of seconds after which a cache part is removed
  95. * `prefix` is a prefix added to every cache key (use the environment in the prefix to use different cache depending on the environment). Use the same prefix for two applications if you want their cache to be shared.
  96. Then, for each particular factory, you have to define the location of the cache storage.
  97. * for `sfFileCache`, the `cache_dir` parameter locates the absolute path to the cache directory
  98. * `sfAPCCache`, `sfEAcceleratorCache`, and `sfXCacheCache` don't take any location parameter, since they use PHP native functions for communicating with APC, EAccelerator or the XCache cache systems
  99. * for `sfMemcacheCache`, enter the hostname of the Memcached server in the `host` parameter, or an array of hosts in the `servers` parameter
  100. * for `sfSQLiteCache`, the absolute path to the SQLite database file should be entered in the `database` parameter
  101. For additional parameters, check the API documentation of each cache class.
  102. The view is not the only component to be able to use a cache. Both the `routing` and the `I18N` factories offer a `cache` parameter in which you can set any cache factory, just like the view cache. For instance, Listing 19-1 shows of the routing uses the file cache for its speedup tactics by default, but you can change it to whatever you want.
  103. #### Logging Settings
  104. Two logging settings (see Chapter 16) are stored in `settings.yml`:
  105. * `error_reporting` specifies which events are logged in the PHP logs. By default, it is set to `E_PARSE | E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR | E_USER_ERROR` for the production environment (so the logged events are `E_PARSE`, `E_COMPILE_ERROR`, `E_ERROR`, `E_CORE_ERROR`, and `E_USER_ERROR`) and to `E_ALL | E_STRICT` for the development environment.
  106. * The `web_debug` setting activates the web debug toolbar. Set it to `on` only in the development and test environments.
  107. #### Paths to Assets
  108. The `settings.yml` file also stores paths to assets. If you want to use another version of the asset than the one bundled with symfony, you can change these path settings:
  109. * Rich text editor JavaScript files stored in `rich_text_js_dir` (by default, `js/tiny_mce`)
  110. * Prototype libraries stored in `prototype_web_dir` (by default, `/sf/prototype`)
  111. * Files needed by the administration generator stored in `admin_web_dir`
  112. * Files needed by the web debug toolbar stored in `web_debug_web_dir`
  113. * Files needed by the javascript calendar stored in `calendar_web_dir`
  114. #### Default Helpers
  115. Default helpers, loaded for every template, are declared in the `standard_helpers` setting (see Chapter 7). By default, these are the `Partial`, `Cache`, and `Form` helper groups. If you use a helper group in all templates of an application, adding its name to the `standard_helpers` setting saves you the hassle of declaring it with `use_helper()` on each template.
  116. #### Activated Modules
  117. Activated modules from plug-ins or from the symfony core are declared in the `enabled_modules` parameter. Even if a plug-in bundles a module, users can't request this module unless it is declared in `enabled_modules`. The `default` module, which provides the default symfony pages (congratulations, page not found, and so on), is the only enabled module by default.
  118. #### Character Set
  119. The character set of the responses is a general setting of the application, because it is used by many components of the framework (templates, output escaper, helpers, and so on). Defined in the `charset` setting, its default (and advised) value is `utf-8`.
  120. #### Miscellaneous Configuration
  121. The `settings.yml` file contains a few more parameters, used internally by symfony for core behaviors. Listing 19-3 lists them as they appear in the configuration file.
  122. Listing 19-3 - Miscellaneous Configuration Settings, in `frontend/config/settings.yml`
  123. # Remove comments in core framework classes as defined in the core_compile.yml
  124. strip_comments: on
  125. # Maximum number of forwards followed by the action before raising an exception
  126. max_forwards: 5
  127. # Global constants
  128. path_info_array: SERVER
  129. path_info_key: PATH_INFO
  130. url_format: PATH
  131. >**SIDEBAR**
  132. >Adding Your application settings
  133. >
  134. >The `settings.yml` file defines symfony settings for an application. As discussed in Chapter 5, when you want to add new parameters, the best place to do so is in the `frontend/config/app.yml` file. This file is also environment-dependent, and the settings it defines are available through the sfConfig class with the `app_` prefix.
  135. >
  136. >
  137. > all:
  138. > creditcards:
  139. > fake: off # app_creditcards_fake
  140. > visa: on # app_creditcards_visa
  141. > americanexpress: on # app_creditcards_americanexpress
  142. >
  143. >
  144. >You can also write an `app.yml` file in the project configuration directory, and this provides a way to define custom project settings. The configuration cascade also applies to this file, so the settings defined in the application `app.yml` file override the ones defined at the project level.
  145. Extending the Autoloading Feature
  146. ---------------------------------
  147. The autoloading feature, briefly explained in Chapter 2, exempts you from requiring classes in your code if they are located in specific directories. This means that you can just let the framework do the job for you, allowing it to load only the necessary classes at the appropriate time, and only when needed.
  148. The `autoload.yml` file lists the paths in which autoloaded classes are stored. The first time this configuration file is processed, symfony parses all the directories referenced in the file. Each time a file ending with `.php` is found in one of these directories, the file path and the class names found in this file are added to an internal list of autoloading classes. This list is saved in the cache, in a file called `config/config_autoload.yml.php`. Then, at runtime, when a class is used, symfony looks in this list for the class path and includes the `.php` file automatically.
  149. Autoloading works for all `.php` files containing classes and/or interfaces.
  150. By default, classes stored in the following directories in your projects benefit from the autoloading automatically:
  151. * `myproject/lib/`
  152. * `myproject/lib/model`
  153. * `myproject/apps/frontend/lib/`
  154. * `myproject/apps/frontend/modules/mymodule/lib`
  155. There is no `autoload.yml` file in the default application configuration directory. If you want to modify the framework settings--for instance, to autoload classes stored somewhere else in your file structure--create an empty autoload.yml file and override the settings of `$sf_symfony_lib_dir/config/config/autoload.yml` or add your own.
  156. The autoload.yml file must start with an autoload: key and list the locations where symfony should look for classes. Each location requires a label; this gives you the ability to override symfony's entries. For each location, provide a `name` (it will appear as a comment in `config_autoload.yml.php`) and an absolute `path`. Then define if the search must be `recursive`, which directs symfony to look in all the subdirectories for `.php` files, and `exclude` the subdirectories you want. Listing 19-4 shows the locations used by default and the file syntax.
  157. Listing 19-4 - Default Autoloading Configuration, in `$sf_symfony_lib_dir/config/config/autoload.yml`
  158. autoload:
  159. # plugins
  160. plugins_lib:
  161. name: plugins lib
  162. path: %SF_PLUGINS_DIR%/*/lib
  163. recursive: on
  164. plugins_module_lib:
  165. name: plugins module lib
  166. path: %SF_PLUGINS_DIR%/*/modules/*/lib
  167. prefix: 2
  168. recursive: on
  169. # project
  170. project:
  171. name: project
  172. path: %SF_LIB_DIR%
  173. recursive: on
  174. exclude: [model, symfony]
  175. project_model:
  176. name: project model
  177. path: %SF_LIB_DIR%/model
  178. recursive: on
  179. # application
  180. application:
  181. name: application
  182. path: %SF_APP_LIB_DIR%
  183. recursive: on
  184. modules:
  185. name: module
  186. path: %SF_APP_DIR%/modules/*/lib
  187. prefix: 1
  188. recursive: on
  189. A rule path can contain wildcards and use the file path parameters defined in the configuration classes (see the next section). If you use these parameters in the configuration file, they must appear in uppercase and begin and end with `%`.
  190. Editing your own `autoload.yml` will add new locations to symfony's autoloading, but you may want to extend this mechanism and add your own autoloading handler to symfony's handler. As symfony uses the standard `spl_autoload_register()` function to manage class autoloading, you can register more callbacks in the application configuration class:
  191. [php]
  192. class frontendConfiguration extends sfApplicationConfiguration
  193. {
  194. public function initialize()
  195. {
  196. parent::initialize(); // load symfony autoloading first
  197. // insert your own autoloading callables here
  198. spl_autoload_register(array('myToolkit', 'autoload'));
  199. }
  200. }
  201. When the PHP autoloading system encounters a new class, it will first try the symfony autoloading method (and use the locations defined in `autoload.yml`). If it doesn't find a class definition, all the other callables registered with `spl_autoload_register()` will be called, until the class is found. So you can add as many autoloading mechanisms as you want--for instance, to provide a bridge to other framework components (see Chapter 17).
  202. Custom File Structure
  203. ---------------------
  204. Each time the framework uses a path to look for something (from core classes to templates, plug-ins, configurations, and so on), it uses a path variable instead of an actual path. By changing these variables, you can completely alter the directory structure of a symfony project, and adapt to the file organization requirements of any client.
  205. >**CAUTION**
  206. >Customizing the directory structure of a symfony project is possible but not necessarily a good idea. One of the strengths of a framework like symfony is that any web developer can look at a project built with it and feel at home, because of the respect for conventions. Make sure you consider this issue before deciding to use your own directory structure.
  207. ### The Basic File Structure
  208. The path variables are defined in the `sfProjectConfiguration` and `sfApplicationConfiguration` classes and stored in the `sfConfig` object. Listing 19-5 shows a listing of the path variables and the directory they reference.
  209. Listing 19-5 - Default File Structure Variables, defined in `sfProjectConfiguration` and `sfApplicationConfiguration`
  210. sf_root_dir # myproject/
  211. sf_apps_dir # apps/
  212. sf_app_dir # frontend/
  213. sf_app_config_dir # config/
  214. sf_app_i18n_dir # i18n/
  215. sf_app_lib_dir # lib/
  216. sf_app_module_dir # modules/
  217. sf_app_template_dir # templates/
  218. sf_cache_dir # cache/
  219. sf_app_base_cache_dir # frontend/
  220. sf_app_cache_dir # prod/
  221. sf_template_cache_dir # templates/
  222. sf_i18n_cache_dir # i18n/
  223. sf_config_cache_dir # config/
  224. sf_test_cache_dir # test/
  225. sf_module_cache_dir # modules/
  226. sf_config_dir # config/
  227. sf_data_dir # data/
  228. sf_doc_dir # doc/
  229. sf_lib_dir # lib/
  230. sf_log_dir # log/
  231. sf_test_dir # test/
  232. sf_plugins_dir # plugins/
  233. sf_web_dir # web/
  234. sf_upload_dir # uploads/
  235. Every path to a key directory is determined by a parameter ending with `_dir`. Always use the path variables instead of real (relative or absolute) file paths, so that you will be able to change them later, if necessary. For instance, when you want to move a file to the `uploads/` directory in an application, you should use `sfConfig::get('sf_upload_dir')` for the path instead of `sfConfig::get('sf_root_dir').'/web/uploads/'`.
  236. ### Customizing the File Structure
  237. You will probably need to modify the default project file structure if you develop an application for a client who already has a defined directory structure and who is not willing to change it to comply with the symfony logic. By overriding the `sf_XXX_dir` variables with `sfConfig`, you can make symfony work for a totally different directory structure than the default structure. The best place to do this is in the application `ProjectConfiguration` class for project directories, or `XXXConfiguration` class for applications directories.
  238. For instance, if you want all applications to share a common directory for the template layouts, add this line to the `configure()` method of the `ProjectConfiguration` class to override the `sf_app_template_dir` settings:
  239. [php]
  240. sfConfig::set('sf_app_template_dir', sfConfig::get('sf_root_dir').DIRECTORY_SEPARATOR.'templates');
  241. >**Note**
  242. >Even if you can change your project directory structure by calling `sfConfig::set()`, it's better to use the dedicated methods defined by the project and application configuration classes if possible as they take care of changing all the related paths. For example, the `setCacheDir()` method changes the following constants: `sf_cache_dir`, `sf_app_base_cache_dir`, `sf_app_cache_dir`, `sf_template_cache_dir`, `sf_i18n_cache_dir`, `sf_config_cache_dir`, `sf_test_cache_dir`, and `sf_module_cache_dir`.
  243. ### Modifying the Project Web Root
  244. All the paths built in the configuration classes rely on the project root directory, which is determined by the `ProjectConfiguration` file included in the front controller. Usually, the root directory is one level above the `web/` directory, but you can use a different structure. Suppose that your main directory structure is made of two directories, one public and one private, as shown in Listing 19-7. This typically happens when hosting a project on a shared host.
  245. Listing 19-7 - Example of Custom Directory Structure for a Shared Host
  246. symfony/ # Private area
  247. apps/
  248. config/
  249. ...
  250. www/ # Public area
  251. images/
  252. css/
  253. js/
  254. index.php
  255. In this case, the root directory is the `symfony/` directory. So the `index.php` front controller simply needs to include the `config/ProjectConfiguration.class.php` file as follows for the application to work:
  256. [php]
  257. require_once(dirname(__FILE__).'/../symfony/config/ProjectConfiguration.class.php');
  258. In addition, use the `setWebDir()` method to change the public area from the usual `web/` to `www/`, as follows:
  259. [php]
  260. class ProjectConfiguration extends sfProjectConfiguration
  261. {
  262. public function setup()
  263. {
  264. // ...
  265. $this->setWebDir($this->getRootDir().'/../www');
  266. }
  267. }
  268. ### Linking to Symfony Libraries
  269. The path to the framework files is defined in the `ProjectConfiguration` class, located in the `config/` directory, as you can see in Listing 19-8.
  270. Listing 19-8 - The Path to the Framework Files, in `myproject/config/ProjectConfiguration.class.php`
  271. [php]
  272. <?php
  273. require_once '/path/to/symfony/lib/autoload/sfCoreAutoload.class.php';
  274. sfCoreAutoload::register();
  275. class ProjectConfiguration extends sfProjectConfiguration
  276. {
  277. public function setup()
  278. {
  279. }
  280. }
  281. The path is initialized when you call a `php symfony generate:project` from the command line, and refer to the symfony installation used to build the project. It is used both by the command line and by the MVC architecture.
  282. This means that you can switch to another installation of symfony by changing the path to the framework files.
  283. The path should be absolute, but by using `dirname(__FILE__)`, you can refer to files inside the project structure and preserve independence of the chosen directory for the project installation. For instance, many projects choose to have the symfony `lib/` directory appear as a symbolic link in the project `lib/vendor/symfony/` directory, as follows:
  284. myproject/
  285. lib/
  286. vendor/
  287. symfony/ => /path/to/symfony/
  288. In this case, the `ProjectConfiguration` class just needs to define the symfony lib directory as follows:
  289. [php]
  290. <?php
  291. require_once dirname(__FILE__).'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
  292. sfCoreAutoload::register();
  293. class ProjectConfiguration extends sfProjectConfiguration
  294. {
  295. public function setup()
  296. {
  297. }
  298. }
  299. The same principle also applies if you choose to include the symfony files as a `svn:externals` in the project `lib/vendor/` directory:
  300. myproject/
  301. lib/
  302. vendor/
  303. svn:externals symfony http://svn.symfony-project.com/branches/1.1
  304. >**TIP**
  305. >Sometimes, the different servers running an application don't have the same path to the symfony libraries. One way to enable that is to exclude the `ProjectConfiguration.class.php` file from the synchronization (by adding it to `rsync_exclude.txt`). Another method is to keep the same paths in the development and production versions of `ProjectConfiguration.class.php`, but to have these paths point to symbolic links that can vary according to the server.
  306. Understanding Configuration Handlers
  307. ------------------------------------
  308. Each configuration file has a handler. The job of configuration handlers is to manage the configuration cascade, and to do the translation between the configuration files and the optimized PHP code executable at runtime.
  309. ### Default Configuration Handlers
  310. The default handler configuration is stored in `$sf_symfony_lib_dir/config/config/config_handlers.yml`. This file links the handlers to the configuration files according to a file path. Listing 19-9 shows an extract of this file.
  311. Listing 19-9 - Extract of `$sf_symfony_lib_dir/config/config/config_handlers.yml`
  312. config/settings.yml:
  313. class: sfDefineEnvironmentConfigHandler
  314. param:
  315. prefix: sf_
  316. config/app.yml:
  317. class: sfDefineEnvironmentConfigHandler
  318. param:
  319. prefix: app_
  320. config/filters.yml:
  321. class: sfFilterConfigHandler
  322. modules/*/config/module.yml:
  323. class: sfDefineEnvironmentConfigHandler
  324. param:
  325. prefix: mod_
  326. module: yes
  327. For each configuration file (`config_handlers.yml` identifies each file by a file path with wildcards), the handler class is specified under the `class` key.
  328. The settings of configuration files handled by `sfDefineEnvironmentConfigHandler` can be made available directly in the code via the `sfConfig` class, and the param key contains a prefix value.
  329. You can add or modify the handlers used to process each configuration file--for instance, to use INI or XML files instead of YAML files.
  330. >**NOTE**
  331. >The configuration handler for the `config_handlers.yml` file is `sfRootConfigHandler` and, obviously, it cannot be changed.
  332. If you ever need to modify the way the configuration is parsed, create an empty `config_handlers.yml` file in your application's `config/` folder and override the `class` lines with the classes you wrote.
  333. ### Adding Your Own Handler
  334. Using a handler to deal with a configuration file provides two important benefits:
  335. * The configuration file is transformed into executable PHP code, and this code is stored in the cache. This means that the configuration is parsed only once in production, and the performance is optimal.
  336. * The configuration file can be defined at different levels (project and application) and the final parameter values will result from a cascade. So you can define parameters at a project level and override them on a per-application basis.
  337. If you feel like writing your own configuration handler, follow the example of the structure used by the framework in the `$sf_symfony_lib_dir/config/` directory.
  338. Let's suppose that your application contains a `myMapAPI` class, which provides an interface to a third-party web service delivering maps. This class needs to be initialized with a URL and a user name, as shown in Listing 19-10.
  339. Listing 19-10 - Example of Initialization of the `myMapAPI` Class
  340. [php]
  341. $mapApi = new myMapAPI();
  342. $mapApi->setUrl($url);
  343. $mapApi->setUser($user);
  344. You may want to store these two parameters in a custom configuration file called `map.yml`, located in the application config/ directory. This configuration file might contain the following:
  345. api:
  346. url: map.api.example.com
  347. user: foobar
  348. In order to transform these settings into code equivalent to Listing 19-9, you must build a configuration handler. Each configuration handler must extend `sfConfigHandler` and provide an `execute()` method, which expects an array of file paths to configuration files as a parameter, and must return data to be written in a cache file. Handlers for YAML files should extend the `sfYamlConfigHandler` class, which provides additional facilities for YAML parsing. For the `map.yml` file, a typical configuration handler could be written as shown in Listing 19-11.
  349. Listing 19-11 - A Custom Configuration Handler, in `frontend/lib/myMapConfigHandler.class.php`
  350. [php]
  351. <?php
  352. class myMapConfigHandler extends sfYamlConfigHandler
  353. {
  354. public function execute($configFiles)
  355. {
  356. // Parse the yaml
  357. $config = $this->parseYamls($configFiles);
  358. $data = "<?php\n";
  359. $data. = "\$mapApi = new myMapAPI();\n";
  360. if (isset($config['api']['url'])
  361. {
  362. $data. = sprintf("\$mapApi->setUrl('%s');\n", $config['api']['url']);
  363. }
  364. if (isset($config['api']['user'])
  365. {
  366. $data. = sprintf("\$mapApi->setUser('%s');\n", $config['api']['user']);
  367. }
  368. return $data;
  369. }
  370. }
  371. The `$configFiles` array that symfony passes to the `execute()` method will contain a path to all the `map.yml` files found in the `config/` folders. The `parseYamls()` method will handle the configuration cascade.
  372. In order to associate this new handler with the `map.yml` file, you must create a `config_handlers.yml` configuration file with the following content:
  373. config/map.yml:
  374. class: myMapConfigHandler
  375. >**NOTE**
  376. >The `class` must either be autoloaded (that's the case here) or defined in the file whose path is written in a `file` parameter under the `param` key.
  377. As with many other symfony configuration files, you can also register a configuration handler directly in your PHP code:
  378. sfContext::getInstance()->getConfigCache()->registerConfigHandler('config/map.yml', 'myMapConfigHandler', array());
  379. When you need the code based on the `map.yml` file and generated by the `myMapConfigHandler` handler in your application, call the following line:
  380. [php]
  381. include(sfContext::getInstance()->getConfigCache()->checkConfig('config/map.yml'));
  382. When calling the `checkConfig()` method, symfony looks for existing `map.yml` files in the configuration directories and processes them with the handler specified in the `config_handlers.yml` file, if a `map.yml.php` does not already exist in the cache or if the `map.yml` file is more recent than the cache.
  383. >**TIP**
  384. >If you want to handle environments in a YAML configuration file, the handler can extend the `sfDefineEnvironmentConfigHandler` class instead of `sfYamlConfigHandler`. Instead of calling the `parseYaml()` method to retrieve the configuration, you should call the `getConfiguration()` method: `$config = $this->getConfiguration($configFiles)`.
  385. -
  386. >**SIDEBAR**
  387. >Using Existing configuration handlers
  388. >
  389. >If you just need to allow users to retrieve values from the code via `sfConfig`, you can use the `sfDefineEnvironmentConfigHandler` configuration handler class. For instance, to have the `url` and `user` parameters available as `sfConfig::get('map_url')` and `sfConfig::get('map_user')`, define your handler as follows:
  390. >
  391. > config/map.yml:
  392. > class: sfDefineEnvironmentConfigHandler
  393. > param:
  394. > prefix: map_
  395. >
  396. >Be careful not to choose a prefix already used by another handler. Existing prefixes are `sf_`, `app_`, and `mod_`.
  397. Summary
  398. -------
  399. The configuration files can heavily modify the way the framework works. Because symfony relies on configuration even for its core features and file loading, it can adapt to many more environments than just the standard dedicated host. This great configurability is one of the main strengths of symfony. Even if it sometimes frightens newcomers, who see in configuration files a lot of conventions to learn, it allows symfony applications to be compatible with a very large number of platforms and environments. Once you become a master of symfony's configuration, no server will ever refuse to run your applications!