[ Index ]
 

Code source de Symfony 1.0.0

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/doc/ -> 16-Application-Management-Tools.txt (source)

   1  Chapter 16 - Application Management Tools
   2  =========================================
   3  
   4  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.
   5  
   6  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.
   7  
   8  This chapter explains how symfony application management tools can answer all these needs.
   9  
  10  Logging
  11  -------
  12  
  13  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.
  14  
  15  ### PHP Logs
  16  
  17  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.
  18  
  19  Listing 16-1 - Setting the Error Reporting Level, in `myapp/config/settings.yml`
  20  
  21      prod:
  22       .settings:
  23          error_reporting:  257
  24  
  25      dev:
  26        .settings:
  27          error_reporting:  4095
  28  
  29  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).
  30  
  31  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.
  32  
  33  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.
  34  
  35  ### Symfony Logs
  36  
  37  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.
  38  
  39  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.
  40  
  41  Listing 16-2 - Sample Symfony Log File Content, in `log/myapp_dev.php`
  42  
  43      Nov 15 16:30:25 symfony [info ] {sfAction} call "barActions->executemessages()"
  44      Nov 15 16:30:25 symfony [debug] SELECT bd_message.ID, bd_message.SENDER_ID, bd_...
  45      Nov 15 16:30:25 symfony [info ] {sfCreole} executeQuery(): SELECT bd_message.ID...
  46      Nov 15 16:30:25 symfony [info ] {sfView} set slot "leftbar" (bar/index)
  47      Nov 15 16:30:25 symfony [info ] {sfView} set slot "messageblock" (bar/mes...
  48      Nov 15 16:30:25 symfony [info ] {sfView} execute view for template "messa...
  49      Nov 15 16:30:25 symfony [info ] {sfView} render "/home/production/myproject/...
  50      Nov 15 16:30:25 symfony [info ] {sfView} render to client
  51  
  52  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.
  53  
  54  #### Symfony Log Level Configuration
  55  
  56  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.
  57  
  58  Listing 16-3 - Default Logging Configuration, in `myapp/config/logging.yml`
  59  
  60      prod:
  61        enabled: off
  62        level:   err
  63        rotate:  on
  64        purge:   off
  65  
  66      dev:
  67  
  68      test:
  69  
  70      #all:
  71      #  enabled:  on
  72      #  level:    debug
  73      #  rotate:   off
  74      #  period:   7
  75      #  history:  10
  76      #  purge:    on
  77  
  78  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.
  79  
  80  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.
  81  
  82  >**TIP**
  83  >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')`.
  84  
  85  #### Adding a Log Message
  86  
  87  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.
  88  
  89  Listing 16-4 - Adding a Custom Log Message
  90  
  91      [php]
  92      // From an action
  93      $this->logMessage($message, $level);
  94  
  95      // From a template
  96      <?php use_helper('Debug') ?>
  97      <?php log_message($message, $level) ?>
  98  
  99  `$level` can have the same values as in the log messages.
 100  
 101  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.
 102  
 103  Listing 16-5 - Adding a Custom Log Message from Anywhere
 104  
 105      [php]
 106      if (sfConfig::get('sf_logging_enabled'))
 107      {
 108        sfContext::getInstance()->getLogger()->info($message);
 109      }
 110  
 111  >**SIDEBAR**
 112  >Customizing the logging
 113  >
 114  >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`:
 115  >
 116  >     [php]
 117  >     require_once('Log.php');
 118  >     $log = Log::singleton('error_log', PEAR_LOG_TYPE_SYSTEM, 'symfony');
 119  >     sfLogger::getInstance()->registerLogger($log);
 120  >
 121  >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).
 122  
 123  #### Purging and Rotating Log Files
 124  
 125  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):
 126  
 127      > symfony log-purge
 128  
 129  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.
 130  
 131  Listing 16-6 - Configuring Log Rotation, in `myapp/config/logging.yml`
 132  
 133      prod:
 134        rotate:  on
 135        period:  7       ## Log files are rotated every 7 days by default
 136        history: 10      ## A maximum history of 10 log files is kept
 137  
 138  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:
 139  
 140      > symfony log-rotate myapp prod
 141  
 142  The backup log files are stored in the `logs/history/` directory and suffixed with the date they were saved.
 143  
 144  Debugging
 145  ---------
 146  
 147  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.
 148  
 149  ### Symfony Debug Mode
 150  
 151  Symfony has a debug mode that facilitates application development and debugging. When it is on, the following happens:
 152  
 153    * 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.
 154    * The error messages display the full stack trace in a clear and useful way, so that you can more efficiently find the faulty element.
 155    * More debug tools are available (such as the detail of database queries).
 156    * 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.
 157  
 158  On the other hand, when the debug mode is off, processing is handled as follows:
 159  
 160    * 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.
 161    * To allow a reprocessing of the configuration, you must manually clear the configuration cache.
 162    * 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.
 163  
 164  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.
 165  
 166  Listing 16-7 - Sample Front Controller with Debug Mode On, in `web/myapp_dev.php`
 167  
 168      [php]
 169      <?php
 170  
 171      define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
 172      define('SF_APP',         'myapp');
 173      define('SF_ENVIRONMENT', 'dev');
 174      define('SF_DEBUG',       true);
 175  
 176      require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
 177  
 178      sfContext::getInstance()->getController()->dispatch();
 179  
 180  >**CAUTION**
 181  >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.
 182  
 183  ### Symfony Exceptions
 184  
 185  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.
 186  
 187  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.
 188  
 189  >**NOTE**
 190  >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`.
 191  
 192  Figure 16-1 - Sample exception message for a symfony application
 193  
 194  ![Sample exception message for a symfony application](/images/book/F1601.png "Sample exception message for a symfony application")
 195  
 196  During the development phase, the symfony exceptions will be of great use as you debug your application.
 197  
 198  ### Xdebug Extension
 199  
 200  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:
 201  
 202      zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20041030/xdebug.so"
 203  
 204  For Windows platforms, the Xdebug activation is triggered by this line:
 205  
 206      extension=php_xdebug.dll
 207  
 208  Listing 16-8 gives an example of Xdebug configuration, which must also be added to the `php.ini` file.
 209  
 210  Listing 16-8 - Sample Xdebug Configuration
 211  
 212      ;xdebug.profiler_enable=1
 213      ;xdebug.profiler_output_dir="/tmp/xdebug"
 214      xdebug.auto_trace=1             ; enable tracing
 215      xdebug.trace_format=0
 216      ;xdebug.show_mem_delta=0        ; memory difference
 217      ;xdebug.show_local_vars=1
 218      ;xdebug.max_nesting_level=100
 219  
 220  You must restart your web server for the Xdebug mode to be activated.
 221  
 222  >**CAUTION**
 223  >Don't forget to deactivate Xdebug mode in your production platform. Not doing so will slow down the execution of every page a lot.
 224  
 225  ### Web Debug Toolbar
 226  
 227  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.
 228  
 229  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.
 230  
 231  Figure 16-2 - The web debug toolbar appears in the top-right corner of the window
 232  
 233  ![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")
 234  
 235  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.
 236  
 237  >**NOTE**
 238  >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.
 239  
 240  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.
 241  
 242  Listing 16-9 - Web Debug Toolbar Activation, in `myapp/config/settings.yml`
 243  
 244      dev:
 245        .settings:
 246          web_debug:              on
 247  
 248  When displayed, the web debug toolbar offers a lot of information/interaction:
 249  
 250    * 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.
 251    * 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).
 252  
 253  Figure 16-3 - The vars & config section shows all the variables and constants of the request
 254  
 255  ![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")
 256  
 257    * 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).
 258    * 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.
 259  
 260  Figure 16-4 - The logs & msgs section shows the log messages for the current request
 261  
 262  ![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")
 263  
 264  >**NOTE**
 265  >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.
 266  
 267    * 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.
 268    * 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.
 269    * Click the red x at the right end of the toolbar to hide the toolbar.
 270  
 271  Figure 16-5 - The database queries section shows queries executed for the current request
 272  
 273  ![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")
 274  
 275  Figure 16-6 - The clock icon shows execution time by category
 276  
 277  ![The clock icon shows execution time by category](/images/book/F1606.png "The clock icon shows execution time by category")
 278  
 279  >**SIDEBAR**
 280  >Adding your own timer
 281  >
 282  >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.
 283  >
 284  >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.
 285  >
 286  >     [php]
 287  >     // Initialize the timer and start timing
 288  >     $timer = sfTimerManager::getTimer('myTimer');
 289  >
 290  >     // Do things
 291  >     ...
 292  >
 293  >     // Stop the timer and add the elapsed time
 294  >     $timer->addTime();
 295  >
 296  >     // Get the result (and stop the timer if not already stopped)
 297  >     $elapsedTime = $timer->getElapsedTime();
 298  >
 299  >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.
 300  >
 301  >     [php]
 302  >     // Get the number of calls to the timer
 303  >     $nbCalls = $timer->getCalls();
 304  >
 305  >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.
 306  
 307  >**NOTE**
 308  >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)`.
 309  
 310  ### Manual Debugging
 311  
 312  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.
 313  
 314  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).
 315  
 316  Listing 16-10 - Inserting a Message in the Log for Debugging Purposes
 317  
 318      [php]
 319      <?php use_helper('Debug') ?>
 320      ...
 321      <?php if ($problem): ?>
 322        <?php log_message('{sfAction} been there', 'err') ?>
 323        ...
 324      <?php endif ?>
 325  
 326  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.
 327  
 328  Figure 16-7 - A custom log message appears in the logs & msgs section of the web debug toolbar
 329  
 330  ![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")
 331  
 332  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.
 333  
 334  Listing 16-11 - Inserting a Message in the Debug Toolbar
 335  
 336      [php]
 337      // From an action
 338      $this->debugMessage($message);
 339  
 340      // From a template
 341      <?php use_helper('Debug') ?>
 342      <?php debug_message($message) ?>
 343  
 344  Populating a Database
 345  ---------------------
 346  
 347  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.
 348  
 349  ### Fixture File Syntax
 350  
 351  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.
 352  
 353  Listing 16-12 - Sample Fixture File, in `data/fixtures/import_data.yml`
 354  
 355      Article:                             ## Insert records in the blog_article table
 356        first_post:                        ## First record label
 357          title:       My first memories
 358          content: |
 359            For a long time I used to go to bed early. Sometimes, when I had put
 360            out my candle, my eyes would close so quickly that I had not even time
 361            to say "I'm going to sleep."
 362  
 363        second_post:                       ## Second record label
 364          title:       Things got worse
 365          content: |
 366            Sometimes he hoped that she would die, painlessly, in some accident,
 367            she who was out of doors in the streets, crossing busy thoroughfares,
 368            from morning to night.
 369  
 370  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).
 371  
 372  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.
 373  
 374  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.
 375  
 376  ### Launching the Import
 377  
 378  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).
 379  
 380      > symfony propel-load-data frontend
 381  
 382  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.
 383  
 384      > symfony propel-load-data frontend append
 385  
 386  You can specify another fixture file or directory in the call. In this case, add a path relative to the project `data/` directory.
 387  
 388      > symfony propel-load-data frontend myfixtures/myfile.yml
 389  
 390  ### Using Linked Tables
 391  
 392  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.
 393  
 394  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.
 395  
 396  Figure 16-8 - A sample database relational model
 397  
 398  ![A sample database relational model](/images/book/F1608.png "A sample database relational model")
 399  
 400  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.
 401  
 402  Listing 16-13 - Adding a Record to a Related Table, in `data/fixtures/import_data.yml`
 403  
 404      Comment:
 405        first_comment:
 406          article_id:   first_post
 407          author:       Anonymous
 408          content:      Your prose is too verbose. Write shorter sentences.
 409  
 410  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.
 411  
 412  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.
 413  
 414  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.
 415  
 416  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.
 417  
 418      100_article_import_data.yml
 419      200_comment_import_data.yml
 420      300_rating_import_data.yml
 421  
 422  Deploying Applications
 423  ----------------------
 424  
 425  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.
 426  
 427  ### Freezing a Project for FTP Transfer
 428  
 429  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.
 430  
 431  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.
 432  
 433      > symfony freeze
 434  
 435  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.
 436  
 437  >**TIP**
 438  >Various frozen projects can work on the same server with different versions of symfony without any problems.
 439  
 440  To revert a project to its initial state, use the `unfreeze` task. It erases the `data/symfony/`, `lib/symfony/`, and `web/sf/` directories.
 441  
 442      > symfony unfreeze
 443  
 444  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.
 445  
 446  ### Using rsync for Incremental File Transfer
 447  
 448  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.
 449  
 450  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.
 451  
 452  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.
 453  
 454  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.
 455  
 456  Listing 16-14 - Sample Connection Settings for a Server Synchronization, in `myproject/config/properties.ini`
 457  
 458      [symfony]
 459        name=myproject
 460  
 461      [production]
 462        host=myapp.example.com
 463        port=22
 464        user=myuser
 465        dir=/home/myaccount/myproject/
 466  
 467  >**NOTE**
 468  >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).
 469  
 470  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:
 471  
 472      > symfony sync production
 473  
 474  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`.
 475  
 476      > symfony sync production go
 477  
 478  Don't forget to clear the cache in the production server after synchronization.
 479  
 480  >**TIP**
 481  >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.
 482  
 483  -
 484  
 485  >**SIDEBAR**
 486  >Is your application finished?
 487  >
 488  >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:
 489  >
 490  >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.
 491  >
 492  >The `default` module should be removed from the `enabled_modules` array in the `settings.yml`, so that no symfony page appear by mistake.
 493  >
 494  >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.
 495  >
 496  >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.
 497  >
 498  >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.
 499  
 500  ### Ignoring Irrelevant Files
 501  
 502  If you synchronize your symfony project with a production host, a few files and directories should not be transferred:
 503  
 504    * All the version control directories (`.svn/`, `CVS/`, and so on) and their content are necessary only for development and integration.
 505    * 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.
 506    * 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.
 507    * 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.
 508  
 509  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.
 510  
 511  Listing 16-15 - Sample rsync Exclusion Settings, in `myproject/config/rsync_exclude.txt`
 512  
 513      .svn
 514      /cache/*
 515      /log/*
 516      /stats/*
 517      /web/uploads/*
 518      /web/myapp_dev.php
 519  
 520  >**NOTE**
 521  >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.
 522  
 523  ### Managing a Production Application
 524  
 525  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.
 526  
 527      > symfony clear-cache
 528  
 529  >**TIP**
 530  >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.
 531  
 532  You can temporarily disable your application--for instance, when you need to upgrade a library or a large amount of data.
 533  
 534      > symfony disable APPLICATION_NAME ENVIRONMENT_NAME
 535  
 536  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.
 537  
 538  Listing 16-16 - Setting the Action to Execute for an Unavailable Application, in `myapp/config/settings.yml`
 539  
 540      all:
 541        .settings:
 542          unavailable_module:     mymodule
 543          unavailable_action:     maintenance
 544  
 545  The `enable` task reenables the application and clears the cache.
 546  
 547      > symfony enable APPLICATION_NAME ENVIRONMENT_NAME
 548  
 549  >**SIDEBAR**
 550  >Displaying an unavailable page when clearing the cache
 551  >
 552  >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.
 553  >
 554  >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.
 555  >
 556  >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.
 557  >
 558  >     > symfony clear-controllers
 559  >
 560  >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).
 561  >
 562  >     > symfony fix-perms
 563  
 564  >**SIDEBAR**
 565  >Access to the symfony commands in production
 566  >
 567  >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:
 568  >
 569  >
 570  >     // With symfony installed via PEAR
 571  >     > symfony [options] <TASK> [parameters]
 572  >
 573  >     // With symfony frozen in the project or symlinked
 574  >     > php symfony [options] <TASK> [parameters]
 575  
 576  Summary
 577  -------
 578  
 579  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.
 580  
 581  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.


Généré le : Fri Mar 16 22:42:14 2007 par Balluche grâce à PHPXref 0.7