PageRenderTime 68ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/vendor/symfony/doc/16-Application-Management-Tools.txt

https://github.com/soon0009/EMS
Plain Text | 581 lines | 384 code | 197 blank | 0 comment | 0 complexity | f7261860af9a1fa89ab12c4691ebfa7d MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1
  1. Chapter 16 - Application Management Tools
  2. =========================================
  3. During both the development and deployment phases, developers require a consistent stream of diagnostic information in order to determine whether the application is working as intended. This information is generally aggregated through logging and debugging utilities. Because of the central role frameworks, such as symfony, play in driving applications, it's crucial that such capabilities are tightly integrated to ensure efficient developmental and operational activities.
  4. During the life of an application on the production server, the application administrator repeats a large number of tasks, from log rotation to upgrades. A framework must also provide tools to automate these tasks as much as possible.
  5. This chapter explains how symfony application management tools can answer all these needs.
  6. Logging
  7. -------
  8. The only way to understand what went wrong during the execution of a request is to review a trace of the execution process. Fortunately, as you'll learn in this section, both PHP and symfony tend to log large amounts of this sort of data.
  9. ### PHP Logs
  10. PHP has an `error_reporting` parameter, defined in `php.ini`, that specifies which PHP events are logged. Symfony allows you to override this value, per application and environment, in the `settings.yml` file, as shown in Listing 16-1.
  11. Listing 16-1 - Setting the Error Reporting Level, in `myapp/config/settings.yml`
  12. prod:
  13. .settings:
  14. error_reporting: 257
  15. dev:
  16. .settings:
  17. error_reporting: 4095
  18. The numbers are a short way of writing error levels (refer to the PHP documentation on error reporting for more details). Basically, `4095` is a shortcut for `E_ALL | E_STRICT`, and `257` stands for `E_ERROR | E_USER_ERROR` (the default value for every new environment).
  19. In order to avoid performance issues in the production environment, the server logs only the critical PHP errors. However, in the development environment, all types of events are logged, so that the developer can have all the information necessary to trace errors.
  20. The location of the PHP log files depends on your `php.ini` configuration. If you never bothered about defining this location, PHP probably uses the logging facilities provided by your web server (such as the Apache error logs). In this case, you will find the PHP logs under the web server log directory.
  21. ### Symfony Logs
  22. In addition to the standard PHP logs, symfony can log a lot of custom events. You can find all the symfony logs under the `myproject/log/` directory. There is one file per application and per environment. For instance, the development environment log file of the `myapp` application is named `myapp_dev.log`, the production one is named `myapp_prod.log`, and so on.
  23. If you have a symfony application running, take a look at its log files. The syntax is very simple. For every event, one line is added to the log file of the application. Each line includes the exact time of the event, the nature of the event, the object being processed, and any additional relevant details. Listing 16-2 shows an example of symfony log file content.
  24. Listing 16-2 - Sample Symfony Log File Content, in `log/myapp_dev.php`
  25. Nov 15 16:30:25 symfony [info ] {sfAction} call "barActions->executemessages()"
  26. Nov 15 16:30:25 symfony [debug] SELECT bd_message.ID, bd_message.SENDER_ID, bd_...
  27. Nov 15 16:30:25 symfony [info ] {sfCreole} executeQuery(): SELECT bd_message.ID...
  28. Nov 15 16:30:25 symfony [info ] {sfView} set slot "leftbar" (bar/index)
  29. Nov 15 16:30:25 symfony [info ] {sfView} set slot "messageblock" (bar/mes...
  30. Nov 15 16:30:25 symfony [info ] {sfView} execute view for template "messa...
  31. Nov 15 16:30:25 symfony [info ] {sfView} render "/home/production/myproject/...
  32. Nov 15 16:30:25 symfony [info ] {sfView} render to client
  33. You can find many details in these files, including the actual SQL queries sent to the database, the templates called, the chain of calls between objects, and so on.
  34. #### Symfony Log Level Configuration
  35. There are eight levels of symfony log messages: `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`, which are the same as the `PEAR::Log` package ([http://pear.php.net/package/Log/](http://pear.php.net/package/Log/)) levels. You can configure the maximum level to be logged in each environment in the `logging.yml` configuration file of each application, as demonstrated in Listing 16-3.
  36. Listing 16-3 - Default Logging Configuration, in `myapp/config/logging.yml`
  37. prod:
  38. enabled: off
  39. level: err
  40. rotate: on
  41. purge: off
  42. dev:
  43. test:
  44. #all:
  45. # enabled: on
  46. # level: debug
  47. # rotate: off
  48. # period: 7
  49. # history: 10
  50. # purge: on
  51. By default, in all environments except the production environment, all the messages are logged (up to the least important level, the `debug` level). In the production environment, logging is disabled by default; if you change `enabled` to `on`, only the most important messages (from `crit` to `emerg`) appear in the logs.
  52. You can change the logging level in the `logging.yml` file for each environment to limit the type of logged messages. The `rotate`, `period`, `history`, and `purge` settings are described in the upcoming "Purging and Rotating Log Files" section.
  53. >**TIP**
  54. >The values of the logging parameters are accessible during execution through the `sfConfig` object with the `sf_logging_` prefix. For instance, to see if logging is enabled, call `sfConfig::get('sf_ logging_enabled')`.
  55. #### Adding a Log Message
  56. You can manually add a message in the symfony log file from your code by using one of the techniques described in Listing 16-4.
  57. Listing 16-4 - Adding a Custom Log Message
  58. [php]
  59. // From an action
  60. $this->logMessage($message, $level);
  61. // From a template
  62. <?php use_helper('Debug') ?>
  63. <?php log_message($message, $level) ?>
  64. `$level` can have the same values as in the log messages.
  65. Alternatively, to write a message in the log from anywhere in your application, use the `sfLogger` methods directly, as shown in Listing 16-5. The available methods bear the same names as the log levels.
  66. Listing 16-5 - Adding a Custom Log Message from Anywhere
  67. [php]
  68. if (sfConfig::get('sf_logging_enabled'))
  69. {
  70. sfContext::getInstance()->getLogger()->info($message);
  71. }
  72. >**SIDEBAR**
  73. >Customizing the logging
  74. >
  75. >Symfony's logging system is very simple, yet it is also easy to customize. You can specify your own logging object by calling `sfLogger::getInstance()->registerLogger()`. For instance, if you want to use `PEAR::Log`, just add the following to your application's `config.php`:
  76. >
  77. > [php]
  78. > require_once('Log.php');
  79. > $log = Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'symfony');
  80. > sfLogger::getInstance()->registerLogger($log);
  81. >
  82. >If you want to register your own logger class, the only prerequisite is that it must define a `log()` method. Symfony calls this method with two parameters: `$message` (the message to be logged) and `$priority` (the level).
  83. #### Purging and Rotating Log Files
  84. Don't forget to periodically purge the `log/` directory of your applications, because these files have the strange habit of growing by several megabytes in a few days, depending, of course, on your traffic. Symfony provides a special `log-purge` task for this purpose, which you can launch regularly by hand or put in a cron table. For example, the following command erases the symfony log files in applications and environments where the logging.yml file specifies purge: on (which is the default value):
  85. > symfony log-purge
  86. For both better performance and security, you probably want to store symfony logs in several small files instead of one single large file. The ideal storage strategy for log files is to back up and empty the main log file regularly, but to keep only a limited number of backups. You can enable such a log rotation and specify the parameters in `logging.yml`. For instance, with a `period` of `7` days and a `history` (number of backups) of `10`, as shown in Listing 16-6, you would work with one active log file plus ten backup files containing seven days' worth of history each. Whenever the next period of seven days ends, the current active log file goes into backup, and the oldest backup is erased.
  87. Listing 16-6 - Configuring Log Rotation, in `myapp/config/logging.yml`
  88. prod:
  89. rotate: on
  90. period: 7 ## Log files are rotated every 7 days by default
  91. history: 10 ## A maximum history of 10 log files is kept
  92. To execute the log rotation, periodically execute the `log-rotate` task. This task only purges files for which `rotate` is `on`. You can specify a single application and environment when calling the task:
  93. > symfony log-rotate myapp prod
  94. The backup log files are stored in the `logs/history/` directory and suffixed with the date they were saved.
  95. Debugging
  96. ---------
  97. No matter how proficient a coder you are, you will eventually make mistakes, even if you use symfony. Detecting and understanding errors is one of the keys of fast application development. Fortunately, symfony provides several debug tools for the developer.
  98. ### Symfony Debug Mode
  99. Symfony has a debug mode that facilitates application development and debugging. When it is on, the following happens:
  100. * The configuration is checked at each request, so a change in any of the configuration files has an immediate effect, without any need to clear the configuration cache.
  101. * The error messages display the full stack trace in a clear and useful way, so that you can more efficiently find the faulty element.
  102. * More debug tools are available (such as the detail of database queries).
  103. * The Propel debug mode is also activated, so any error in a call to a Propel object will display a detailed chain of calls through the Propel architecture.
  104. On the other hand, when the debug mode is off, processing is handled as follows:
  105. * The YAML configuration files are parsed only once, then transformed into PHP files stored in the `cache/config/` folder. Every request after the first one ignores the YAML files and uses the cached configuration instead. As a consequence, the processing of requests is much faster.
  106. * To allow a reprocessing of the configuration, you must manually clear the configuration cache.
  107. * An error during the processing of the request returns a response with code 500 (Internal Server Error), without any explanation of the internal cause of the problem.
  108. The debug mode is activated per application in the front controller. It is controlled by the value of the `SF_DEBUG` constant, as shown in Listing 16-7.
  109. Listing 16-7 - Sample Front Controller with Debug Mode On, in `web/myapp_dev.php`
  110. [php]
  111. <?php
  112. define('SF_ROOT_DIR', realpath(dirname(__FILE__).'/..'));
  113. define('SF_APP', 'myapp');
  114. define('SF_ENVIRONMENT', 'dev');
  115. define('SF_DEBUG', true);
  116. require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
  117. sfContext::getInstance()->getController()->dispatch();
  118. >**CAUTION**
  119. >In your production server, you should not activate the debug mode nor leave any front controller with debug mode on available. Not only will the debug mode slow down the page delivery, but it may also reveal the internals of your application. Even though the debug tools never reveal database connection information, the stack trace of exceptions is full of dangerous information for any ill-intentioned visitor.
  120. ### Symfony Exceptions
  121. When an exception occurs in the debug mode, symfony displays a useful exception notice that contains everything you need to find the cause of the problem.
  122. The exception messages are clearly written and refer to the most probable cause of the problem. They often provide possible solutions to fix the problem, and for most common problems, the exception pages even contain a link to a symfony website page with more details about the exception. The exception page shows where the error occurred in the PHP code (with syntax highlighting), together with the full stack of method calls, as shown in Figure 16-1. You can follow the trace to the first call that caused the problem. The arguments that were passed to the methods are also shown.
  123. >**NOTE**
  124. >Symfony really relies on PHP exceptions for error reporting, which is much better than the way PHP 4 applications work. For instance, the 404 error can be triggered by an `sfError404Exception`.
  125. Figure 16-1 - Sample exception message for a symfony application
  126. ![Sample exception message for a symfony application](/images/book/F1601.png "Sample exception message for a symfony application")
  127. During the development phase, the symfony exceptions will be of great use as you debug your application.
  128. ### Xdebug Extension
  129. The Xdebug PHP extension ([http://xdebug.org/](http://xdebug.org/)) allows you to extend the amount of information that is logged by the web server. Symfony integrates the Xdebug messages in its own debug feedback, so it is a good idea to activate this extension when you debug the application. The extension installation depends very much on your platform; refer to the Xdebug website for detailed installation guidelines. Once Xdebug is installed, you need to activate it manually in your `php.ini` file after installation. For *nix platforms, this is done by adding the following line:
  130. zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20041030/xdebug.so"
  131. For Windows platforms, the Xdebug activation is triggered by this line:
  132. extension=php_xdebug.dll
  133. Listing 16-8 gives an example of Xdebug configuration, which must also be added to the `php.ini` file.
  134. Listing 16-8 - Sample Xdebug Configuration
  135. ;xdebug.profiler_enable=1
  136. ;xdebug.profiler_output_dir="/tmp/xdebug"
  137. xdebug.auto_trace=1 ; enable tracing
  138. xdebug.trace_format=0
  139. ;xdebug.show_mem_delta=0 ; memory difference
  140. ;xdebug.show_local_vars=1
  141. ;xdebug.max_nesting_level=100
  142. You must restart your web server for the Xdebug mode to be activated.
  143. >**CAUTION**
  144. >Don't forget to deactivate Xdebug mode in your production platform. Not doing so will slow down the execution of every page a lot.
  145. ### Web Debug Toolbar
  146. The log files contain interesting information, but they are not very easy to read. The most basic task, which is to find the lines logged for a particular request, can be quite tricky if you have several users simultaneously using an application and a long history of events. That's when you start to need a web debug toolbar.
  147. This toolbar appears as a semitransparent box superimposed over the normal content in the browser, in the top-right corner of the window, as shown in Figure 16-2. It gives access to the symfony log events, the current configuration, the properties of the request and response objects, the details of the database queries issued by the request, and a chart of processing times related to the request.
  148. Figure 16-2 - The web debug toolbar appears in the top-right corner of the window
  149. ![The web debug toolbar appears in the top-right corner of the window](/images/book/F1602.jpg "The web debug toolbar appears in the top-right corner of the window")
  150. The color of the debug toolbar background depends on the highest level of log message issued during the request. If no message passes the `debug` level, the toolbar has a gray background. If a single message reaches the `err` level, the toolbar has a red background.
  151. >**NOTE**
  152. >Don't confuse the debug mode with the web debug toolbar. The debug toolbar can be displayed even when the debug mode if off, although, in that case, it displays much less information.
  153. To activate the web debug toolbar for an application, open the `settings.yml` file and look for the `web_debug` key. In the `prod` and `test` environments, the default value for `web_debug` is `off`, so you need to activate it manually if you want it. In the `dev` environment, the default configuration has it set to `on`, as shown in Listing 16-9.
  154. Listing 16-9 - Web Debug Toolbar Activation, in `myapp/config/settings.yml`
  155. dev:
  156. .settings:
  157. web_debug: on
  158. When displayed, the web debug toolbar offers a lot of information/interaction:
  159. * Click the symfony logo to toggle the visibility of the toolbar. When reduced, the toolbar doesn't hide the elements located at the top of the page.
  160. * Click the vars & config section to show the details of the request, response, settings, globals, and PHP properties, as shown in Figure 16-3. The top line sums up the important configuration settings, such as the debug mode, the cache, and the presence of a PHP accelerator (they appear in red if they are deactivated and in green if they are activated).
  161. Figure 16-3 - The vars & config section shows all the variables and constants of the request
  162. ![The vars & config section shows all the variables and constants of the request](/images/book/F1603.png "The vars & config section shows all the variables and constants of the request")
  163. * When the cache is enabled, a green arrow appears in the toolbar. Click this arrow to reprocess the page, regardless of what is stored in the cache (but the cache is not cleared).
  164. * Click the logs & msgs section to reveal the log messages for the current request, as shown in Figure 16-4. According to the importance of the events, they are displayed in gray, yellow, or red lines. You can filter the events that are displayed by category using the links displayed at the top of the list.
  165. Figure 16-4 - The logs & msgs section shows the log messages for the current request
  166. ![The logs & msgs section shows the log messages for the current request](/images/book/F1604.png "The logs & msgs section shows the log messages for the current request")
  167. >**NOTE**
  168. >When the current action results from a redirect, only the logs of the latest request are present in the logs & msgs pane, so the log files are still indispensable for good debugging.
  169. * For requests executing SQL queries, a database icon appears in the toolbar. Click it to see the detail of the queries, as shown in Figure 16-5.
  170. * To the right of a clock icon is the total time necessary to process the request. Be aware that the web debug toolbar and the debug mode slow down the request execution, so try to refrain from considering the timings per se, and pay attention to only the differences between the execution time of two pages. Click the clock icon to see details of the processing time category by category, as shown in Figure 16-6. Symfony displays the time spent on specific parts of the request processing. Only the times related to the current request make sense for an optimization, so the time spent in the symfony core is not displayed. That's why these times don't sum up to the total time.
  171. * Click the red x at the right end of the toolbar to hide the toolbar.
  172. Figure 16-5 - The database queries section shows queries executed for the current request
  173. ![The database queries section shows queries executed for the current request](/images/book/F1605.png "The database queries section shows queries executed for the current request")
  174. Figure 16-6 - The clock icon shows execution time by category
  175. ![The clock icon shows execution time by category](/images/book/F1606.png "The clock icon shows execution time by category")
  176. >**SIDEBAR**
  177. >Adding your own timer
  178. >
  179. >Symfony uses the `sfTimer` class to calculate the time spent on the configuration, the model, the action, and the view. Using the same object, you can time a custom process and display the result with the other timers in the web debug toolbar. This can be very useful when you work on performance optimizations.
  180. >
  181. >To initialize timing on a specific fragment of code, call the `getTimer()` method. It will return an sfTimer object and start the timing. Call the `addTime()` method on this object to stop the timing. The elapsed time is available through the `getElapsedTime()` method, and displayed in the web debug toolbar with the others.
  182. >
  183. > [php]
  184. > // Initialize the timer and start timing
  185. > $timer = sfTimerManager::getTimer('myTimer');
  186. >
  187. > // Do things
  188. > ...
  189. >
  190. > // Stop the timer and add the elapsed time
  191. > $timer->addTime();
  192. >
  193. > // Get the result (and stop the timer if not already stopped)
  194. > $elapsedTime = $timer->getElapsedTime();
  195. >
  196. >The benefit of giving a name to each timer is that you can call it several times to accumulate timings. For instance, if the `myTimer` timer is used in a utility method that is called twice per request, the second call to the `getTimer('myTimer')` method will restart the timing from the point calculated when `addTime()` was last called, so the timing will add up to the previous one. Calling `getCalls()` on the timer object will give you the number of times the timer was launched, and this data is also displayed in the web debug toolbar.
  197. >
  198. > [php]
  199. > // Get the number of calls to the timer
  200. > $nbCalls = $timer->getCalls();
  201. >
  202. >In Xdebug mode, the log messages are much richer. All the PHP script files and the functions that are called are logged, and symfony knows how to link this information with its internal log. Each line of the log messages table has a double-arrow button, which you can click to see further details about the related request. If something goes wrong, the Xdebug mode gives you the maximum amount of detail to find out why.
  203. >**NOTE**
  204. >The web debug toolbar is not included by default in Ajax responses and documents that have a non-HTML content-type. For the other pages, you can disable the web debug toolbar manually from within an action by simply calling `sfConfig::set('sf_web_debug', false)`.
  205. ### Manual Debugging
  206. Getting access to the framework debug messages is nice, but being able to log your own messages is better. Symfony provides shortcuts, accessible from both actions and templates, to help you trace events and/or values during request execution.
  207. Your custom log messages appear in the symfony log file as well as in the web debug toolbar, just like regular events. (Listing 16-4 gave an example of the custom log message syntax.) A custom message is a good way to check the value of a variable from a template, for instance. Listing 16-10 shows how to use the web debug toolbar for developer's feedback from a template (you can also use `$this->logMessage()` from an action).
  208. Listing 16-10 - Inserting a Message in the Log for Debugging Purposes
  209. [php]
  210. <?php use_helper('Debug') ?>
  211. ...
  212. <?php if ($problem): ?>
  213. <?php log_message('{sfAction} been there', 'err') ?>
  214. ...
  215. <?php endif ?>
  216. The use of the `err` level guarantees that the event will be clearly visible in the list of messages, as shown in Figure 16-7.
  217. Figure 16-7 - A custom log message appears in the logs & msgs section of the web debug toolbar
  218. ![A custom log message appears in the logs & msgs section of the web debug toolbar](/images/book/F1607.png "A custom log message appears in the logs & msgs section of the web debug toolbar")
  219. If you don't want to add a line to the log, but just trace a short message or a value, you should use `debug_message` instead of `log_message`. This action method (a helper with the same name also exists) displays a message in the web debug toolbar, on top of the logs & msgs section. Check Listing 16-11 for an example of using the debug message writer.
  220. Listing 16-11 - Inserting a Message in the Debug Toolbar
  221. [php]
  222. // From an action
  223. $this->debugMessage($message);
  224. // From a template
  225. <?php use_helper('Debug') ?>
  226. <?php debug_message($message) ?>
  227. Populating a Database
  228. ---------------------
  229. In the process of application development, developers are often faced with the problem of database population. A few specific solutions exist for some database systems, but none can be used on top of the object-relational mapping. Thanks to YAML and the `sfPropelData` object, symfony can automatically transfer data from a text source to a database. Although writing a text file source for data may seem like more work than entering the records by hand using a CRUD interface, it will save you time in the long run. You will find this feature very useful for automatically storing and populating the test data for your application.
  230. ### Fixture File Syntax
  231. Symfony can read data files that follow a very simple YAML syntax, provided that they are located under the `data/fixtures/` directory. Fixture files are organized by class, each class section being introduced by the class name as a header. For each class, records labeled with a unique string are defined by a set of `fieldname: value` pairs. Listing 16-12 shows an example of a data file for database population.
  232. Listing 16-12 - Sample Fixture File, in `data/fixtures/import_data.yml`
  233. Article: ## Insert records in the blog_article table
  234. first_post: ## First record label
  235. title: My first memories
  236. content: |
  237. For a long time I used to go to bed early. Sometimes, when I had put
  238. out my candle, my eyes would close so quickly that I had not even time
  239. to say "I'm going to sleep".
  240. second_post: ## Second record label
  241. title: Things got worse
  242. content: |
  243. Sometimes he hoped that she would die, painlessly, in some accident,
  244. she who was out of doors in the streets, crossing busy thoroughfares,
  245. from morning to night.
  246. Symfony translates the column keys into setter methods by using a camelCase converter (`setTitle()`, `setContent()`). This means that you can define a `password` key even if the actual table doesn't have a `password` field--just define a `setPassword()` method in the `User` object, and you can populate other columns based on the password (for instance, a hashed version of the password).
  247. The primary key column doesn't need to be defined. Since it is an auto-increment field, the database layer knows how to determine it.
  248. The `created_at` columns don't need to be set either, because symfony knows that fields named that way must be set to the current system time when created.
  249. ### Launching the Import
  250. The `propel-load-data` task imports data from a YAML file to a database. The connection settings come from the `databases.yml` file, and therefore need an application name to run. Optionally, you can specify an environment name (`dev` by default).
  251. > symfony propel-load-data frontend
  252. This command reads all the YAML fixture files from the `data/fixtures/` directory and inserts the records into the database. By default, it replaces the existing database content, but if the last argument call is `append`, the command will not erase the current data.
  253. > symfony propel-load-data frontend append
  254. You can specify another fixture file or directory in the call. In this case, add a path relative to the project directory.
  255. > symfony propel-load-data frontend data/myfixtures/myfile.yml
  256. ### Using Linked Tables
  257. You now know how to add records to a single table, but how do you add records with foreign keys to another table? Since the primary key is not included in the fixtures data, you need an alternative way to relate records to one another.
  258. Let's return to the example in Chapter 8, where a blog_article table is linked to a `blog_comment` table, as shown in Figure 16-8.
  259. Figure 16-8 - A sample database relational model
  260. ![A sample database relational model](/images/book/F1608.png "A sample database relational model")
  261. This is where the labels given to the records become really useful. To add a `Comment` field to the `first_post` article, you simply need to append the lines shown in Listing 16-13 to the `import_data.yml` data file.
  262. Listing 16-13 - Adding a Record to a Related Table, in `data/fixtures/import_data.yml`
  263. Comment:
  264. first_comment:
  265. article_id: first_post
  266. author: Anonymous
  267. content: Your prose is too verbose. Write shorter sentences.
  268. The `propel-load-data` task will recognize the label that you gave to an article previously in `import_data.yml`, and grab the primary key of the corresponding `Article` record to set the `article_id` field. You don't even see the IDs of the records; you just link them by their labels--it couldn't be simpler.
  269. The only constraint for linked records is that the objects called in a foreign key must be defined earlier in the file; that is, as you would do if you defined them one by one. The data files are parsed from the top to the bottom, and the order in which the records are written is important.
  270. One data file can contain declarations of several classes. But if you need to insert a lot of data for many different tables, your fixture file might get too long to be easily manipulated.
  271. The `propel-load-data` task parses all the files it finds in the `fixtures/` directory, so nothing prevents you from splitting a YAML fixture file into smaller pieces. The important thing to keep in mind is that foreign keys impose a processing order for the tables. To make sure that they are parsed in the correct order, prefix the files with an ordinal number.
  272. 100_article_import_data.yml
  273. 200_comment_import_data.yml
  274. 300_rating_import_data.yml
  275. Deploying Applications
  276. ----------------------
  277. Symfony offers shorthand commands to synchronize two versions of a website. These commands are mostly used to deploy a website from a development server to a final host, connected to the Internet.
  278. ### Freezing a Project for FTP Transfer
  279. The most common way to deploy a project to production is to transfer all its files by FTP (or SFTP). However, symfony projects use the symfony libraries, and unless you develop in a sandbox (which is not recommended), or if the symfony `lib/` and `data/` directories are linked by `svn:externals`, these libraries are not in the project directory. Whether you use a PEAR installation or symbolic links, reproducing the same file structure in production can be time-consuming and tricky.
  280. That's why symfony provides a utility to "freeze" a project--to copy all the necessary symfony libraries into the project `data/`, `lib/`, and `web/` directories. The project then becomes a kind of sandbox, an independent, stand-alone application.
  281. > symfony freeze
  282. Once a project is frozen, you can transfer the project directory into production, and it will work without any need for PEAR, symbolic links, or whatever else.
  283. >**TIP**
  284. >Various frozen projects can work on the same server with different versions of symfony without any problems.
  285. To revert a project to its initial state, use the `unfreeze` task. It erases the `data/symfony/`, `lib/symfony/`, and `web/sf/` directories.
  286. > symfony unfreeze
  287. Note that if you had symbolic links to a symfony installation prior to the freeze, symfony will remember them and re-create the symbolic links in the original location.
  288. ### Using rsync for Incremental File Transfer
  289. Sending the root project directory by FTP is fine for the first transfer, but when you need to upload an update of your application, where only a few files have changed, FTP is not ideal. You need to either transfer the whole project again, which is a waste of time and bandwidth, or browse to the directories where you know that some files changed, and transfer only the ones with different modification dates. That's a time-consuming job, and it is prone to error. In addition, the website can be unavailable or buggy during the time of the transfer.
  290. The solution that is supported by symfony is rsync synchronization through an SSH layer. Rsync ([http://samba.anu.edu.au/rsync/](http://samba.anu.edu.au/rsync/)) is a command-line utility that provides fast incremental file transfer, and it's open source. With incremental transfer, only the modified data will be sent. If a file didn't change, it won't be sent to the host. If a file changed only partially, just the differential will be sent. The major advantage is that rsync synchronizations transfer only a small amount of data and are very fast.
  291. Symfony adds SSH on top of rsync to secure the data transfer. More and more commercial hosts support an SSH tunnel to secure file uploads on their servers, and that's a good practice to avoid security breaches.
  292. The SSH client called by symfony uses connection settings from the `config/properties.ini` file. Listing 16-14 gives an example of connection settings for a production server. Write the settings of your own production server in this file before any synchronization. You can also define a single parameters setting to provide your own rsync command line parameters.
  293. Listing 16-14 - Sample Connection Settings for a Server Synchronization, in `myproject/config/properties.ini`
  294. [symfony]
  295. name=myproject
  296. [production]
  297. host=myapp.example.com
  298. port=22
  299. user=myuser
  300. dir=/home/myaccount/myproject/
  301. >**NOTE**
  302. >Don't confuse the production server (the host server, as defined in the `properties.ini` file of the project) with the production environment (the front controller and configuration used in production, as referred to in the configuration files of an application).
  303. Doing an rsync over SSH requires several commands, and synchronization can occur a lot of times in the life of an application. Fortunately, symfony automates this process with just one command:
  304. > symfony sync production
  305. This command launches the rsync command in dry mode; that is, it shows which files must be synchronized but doesn't actually synchronize them. If you want the synchronization to be done, you need to request it explicitly by adding `go`.
  306. > symfony sync production go
  307. Don't forget to clear the cache in the production server after synchronization.
  308. >**TIP**
  309. >Sometimes bugs appear in production that didn't exist in development. In 90% of the cases, this is due to differences in versions (of PHP, web server, or database) or in configurations. To avoid unpleasant surprises, you should define the target PHP configuration in the `php.yml` file of your application, so that it checks that the development environment applies the same settings. Refer to Chapter 19 for more information about this configuration file.
  310. -
  311. >**SIDEBAR**
  312. >Is your application finished?
  313. >
  314. >Before sending your application to production, you should make sure that it is ready for a public use. Check that the following items are done before actually deciding to deploy the application:
  315. >
  316. >The error pages should be customized to the look and feel of your application. Refer to Chapter 19 to see how to customize the error 500, error 404, and security pages, and to the "Managing a Production Application" section in this chapter to see how to customize the pages displayed when your site is not available.
  317. >
  318. >The `default` module should be removed from the `enabled_modules` array in the `settings.yml`, so that no symfony page appear by mistake.
  319. >
  320. >The session-handling mechanism uses a cookie on the client side, and this cookie is called `symfony` by default. Before deploying your application, you should probably rename it to avoid disclosing the fact that your application uses symfony. Refer to Chapter 6 to see how to customize the cookie name in the `factories.yml` file.
  321. >
  322. >The `robots.txt` file, located in the project's `web/` directory, is empty by default. You should customize it to inform web spiders and other web robots about which parts of a website they can browse and which they should avoid. Most of the time, this file is used to exclude certain URL spaces from being indexed--for instance, resource-intensive pages, pages that don't need indexing (such as bug archives), or infinite URL spaces in which robots could get trapped.
  323. >
  324. >Modern browsers request a `favicon.ico` file when a user first browses to your application, to represent the application with an icon in the address bar and bookmarks folder. Providing such a file will not only make your application's look and feel complete, but it will also prevent a lot of 404 errors from appearing in your server logs.
  325. ### Ignoring Irrelevant Files
  326. If you synchronize your symfony project with a production host, a few files and directories should not be transferred:
  327. * All the version control directories (`.svn/`, `CVS/`, and so on) and their content are necessary only for development and integration.
  328. * The front controller for the development environment must not be available to the final users. The debugging and logging tools available when using the application through this front controller slow down the application and give information about the core variables of your actions. It is something to keep away from the public.
  329. * The `cache/` and `log/` directories of a project must not be erased in the host server each time you do a synchronization. These directories must be ignored as well. If you have a `stats/` directory, it should probably be treated the same way.
  330. * The files uploaded by users should not be transferred. One of the good practices of symfony projects is to store the uploaded files in the `web/uploads/` directory. This allows you to exclude all these files from the synchronization by pointing to only one directory.
  331. To exclude files from rsync synchronizations, open and edit the `rsync_exclude.txt` file under the `myproject/config/` directory. Each line can contain a file, a directory, or a pattern. The symfony file structure is organized logically, and designed to minimize the number of files or directories to exclude manually from the synchronization. See Listing 16-15 for an example.
  332. Listing 16-15 - Sample rsync Exclusion Settings, in `myproject/config/rsync_exclude.txt`
  333. .svn
  334. /cache/*
  335. /log/*
  336. /stats/*
  337. /web/uploads/*
  338. /web/myapp_dev.php
  339. >**NOTE**
  340. >The `cache/` and `log/` directories must not be synchronized with the development server, but they must at least exist in the production server. Create them by hand if the `myproject/` project tree structure doesn't contain them.
  341. ### Managing a Production Application
  342. The command that is used most often in production servers is `clear-cache`. You must run it every time you upgrade symfony or your project (for instance, after calling the `sync` task), and every time you change the configuration in production.
  343. > symfony clear-cache
  344. >**TIP**
  345. >If the command-line interface is not available in your production server, you can still clear the cache manually by erasing the contents of the `cache/` folder.
  346. You can temporarily disable your application--for instance, when you need to upgrade a library or a large amount of data.
  347. > symfony disable APPLICATION_NAME ENVIRONMENT_NAME
  348. By default, a disabled application displays the `default/unavailable` action (stored in the framework), but you can customize the module and action to be used in this case in the `settings.yml` file. Listing 16-16 shows an example.
  349. Listing 16-16 - Setting the Action to Execute for an Unavailable Application, in `myapp/config/settings.yml`
  350. all:
  351. .settings:
  352. unavailable_module: mymodule
  353. unavailable_action: maintenance
  354. The `enable` task reenables the application and clears the cache.
  355. > symfony enable APPLICATION_NAME ENVIRONMENT_NAME
  356. >**SIDEBAR**
  357. >Displaying an unavailable page when clearing the cache
  358. >
  359. >If you set the `check_lock` parameter to `on` in the `settings.yml` file, symfony will lock the application when the cache is being cleared, and all the requests arriving before the cache is finally cleared are then redirected to a page saying that the application is temporarily unavailable. If the cache is large, the delay to clear it may be longer than a few milliseconds, and if your site's traffic is high, this is a recommended setting.
  360. >
  361. >This unavailable page is not the same as the one displayed when you call symfony disable (because while the cache is being cleared, symfony cannot work normally). It is located in the `$sf_symfony_data_dir/web/errors/` directory, but if you create your own `unavailable.php` file in your project's `web/errors/` directory, symfony will use it instead. The `check_lock` parameter is deactivated by default because it has a very slight negative impact on performance.
  362. >
  363. >The `clear-controllers` task clears the `web/` directory of all controllers other than the ones running in a production environment. If you do not include the development front controllers in the `rsync_exclude.txt` file, this command guarantees that a backdoor will not reveal the internals of your application.
  364. >
  365. > > symfony clear-controllers
  366. >
  367. >The permissions of the project files and directories can be broken if you use a checkout from an SVN repository. The `fix-perms` task fixes directory permissions, to change the `log/` and `cache/` permissions to 0777, for example (these directories need to be writable for the framework to work correctly).
  368. >
  369. > > symfony fix-perms
  370. >**SIDEBAR**
  371. >Access to the symfony commands in production
  372. >
  373. >If your production server has a PEAR installation of symfony, then the symfony command line is available from every directory and will work just as it does in development. For frozen projects, however, you need to add `php` before the `symfony` command to be able to launch tasks:
  374. >
  375. >
  376. > // With symfony installed via PEAR
  377. > > symfony [options] <TASK> [parameters]
  378. >
  379. > // With symfony frozen in the project or symlinked
  380. > > php symfony [options] <TASK> [parameters]
  381. Summary
  382. -------
  383. By combining PHP logs and symfony logs, you can monitor and debug your application easily. During development, the debug mode, the exceptions, and the web debug toolbar help you locate problems. You can even insert custom messages in the log files or in the toolbar for easier debugging.
  384. The command-line interface provides a large number of tools that facilitate the management of your applications, during development and production phases. Among others, the data population, freeze, and synchronization tasks are great time-savers.