+ All Categories
Home > Documents > symfony tutorial

symfony tutorial

Date post: 24-Nov-2015
Category:
Upload: pablo-zignani
View: 433 times
Download: 14 times
Share this document with a friend
Description:
Php Framework
195
1
Transcript
  • 1----------------- Brought to you by

  • The symfony Reference Book

    symfony 1.3 & 1.4

    This PDF is brought to you by

    License: Creative Commons Attribution-Share Alike 3.0 Unported LicenseVersion: reference-1.4-en-2009-12-23

  • Table of Contents

    About the Author............................................................................................. 13About Sensio Labs........................................................................................... 14Which symfony Version? ................................................................................. 15Introduction .................................................................................................... 16The YAML Format ........................................................................................... 17

    Scalars ..................................................................................................................... 17Strings ................................................................................................................................ 17Numbers ............................................................................................................................. 18Nulls ................................................................................................................................... 18Booleans ............................................................................................................................. 18Dates................................................................................................................................... 18

    Collections ............................................................................................................... 19Comments ................................................................................................................ 20Dynamic YAML files................................................................................................. 20A Full Length Example ............................................................................................ 22

    Configuration File Principles.......................................................................... 23Cache ....................................................................................................................... 23Constants ................................................................................................................. 23

    Configuration Settings ....................................................................................................... 23Application Settings ........................................................................................................... 24Special Constants ............................................................................................................... 24Directories .......................................................................................................................... 24

    environment-awareness........................................................................................... 25Configuration Cascade ............................................................................................ 25

    The settings.yml Configuration File ............................................................... 27Settings.................................................................................................................... 28The .actions Sub-Section..................................................................................... 29error_404......................................................................................................................... 29login ................................................................................................................................. 29secure ............................................................................................................................... 29module_disabled ............................................................................................................ 29

    The .settings Sub-Section................................................................................... 29escaping_strategy ........................................................................................................ 29escaping_method ............................................................................................................ 30csrf_secret..................................................................................................................... 30charset ............................................................................................................................. 30enabled_modules ............................................................................................................ 30default_timezone .......................................................................................................... 31cache ................................................................................................................................. 31

    Table of Contents iii

    ----------------- Brought to you by

  • etag ................................................................................................................................... 31i18n ................................................................................................................................... 31default_culture ............................................................................................................ 32standard_helpers .......................................................................................................... 32no_script_name .............................................................................................................. 32lazy_cache_key .............................................................................................................. 32file_link_format .......................................................................................................... 32logging_enabled ............................................................................................................ 32web_debug......................................................................................................................... 33error_reporting ............................................................................................................ 33compressed....................................................................................................................... 33use_database .................................................................................................................. 33check_lock....................................................................................................................... 33web_debug_web_dir ........................................................................................................ 34

    The factories.yml Configuration File .............................................................. 35Factories .................................................................................................................. 37mailer .................................................................................................................... 39charset ............................................................................................................................. 39delivery_strategy ........................................................................................................ 39delivery_address .......................................................................................................... 39spool_class..................................................................................................................... 40spool_arguments ............................................................................................................ 40transport......................................................................................................................... 40

    request .................................................................................................................. 41path_info_array ............................................................................................................ 41path_info_key ................................................................................................................ 41formats ............................................................................................................................. 41relative_url_root ........................................................................................................ 41

    response ................................................................................................................ 42send_http_headers ........................................................................................................ 42charset ............................................................................................................................. 39http_protocol ................................................................................................................ 42

    user......................................................................................................................... 42timeout ............................................................................................................................. 43use_flash......................................................................................................................... 43default_culture ............................................................................................................ 43

    storage .................................................................................................................. 43auto_start....................................................................................................................... 43session_name .................................................................................................................. 44session_set_cookie_params() parameters ............................................................... 44session_cache_limiter ............................................................................................... 44Database Storage-specific Options..................................................................................... 44

    view_cache_manager ........................................................................................... 44cache_key_use_vary_headers ..................................................................................... 45cache_key_use_host_name ........................................................................................... 45

    view_cache ............................................................................................................ 45i18n......................................................................................................................... 45source ............................................................................................................................... 46debug ................................................................................................................................. 46untranslated_prefix.................................................................................................... 46untranslated_suffix.................................................................................................... 46cache ................................................................................................................................. 46

    routing .................................................................................................................. 46variable_prefixes ........................................................................................................ 47

    Table of Contents iv

    ----------------- Brought to you by

  • segment_separators...................................................................................................... 47generate_shortest_url ............................................................................................... 47extra_parameters_as_query_string ........................................................................ 47cache ................................................................................................................................. 46suffix ............................................................................................................................... 47load_configuration...................................................................................................... 47lazy_routes_deserialize ........................................................................................... 47lookup_cache_dedicated_keys ................................................................................... 48

    logger .................................................................................................................... 48level ................................................................................................................................. 48loggers ............................................................................................................................. 49

    controller ............................................................................................................ 49Anonymous Cache Factories.................................................................................... 49

    The generator.yml Configuration File ............................................................ 50Creation ................................................................................................................... 50Configuration File.................................................................................................... 50Fields ....................................................................................................................... 51Object Placeholders ................................................................................................. 52Configuration Inheritance ....................................................................................... 52Credentials............................................................................................................... 52Actions Customization ............................................................................................. 52Templates Customization ........................................................................................ 53Look and Feel Customization .................................................................................. 54Available Configuration Options.............................................................................. 55fields .................................................................................................................... 56label ................................................................................................................................. 56help ................................................................................................................................... 56attributes....................................................................................................................... 56credentials..................................................................................................................... 52renderer ........................................................................................................................... 56renderer_arguments...................................................................................................... 57type ................................................................................................................................... 57date_format..................................................................................................................... 57

    actions .................................................................................................................. 58label ................................................................................................................................. 56action ............................................................................................................................... 58credentials..................................................................................................................... 52

    list......................................................................................................................... 58title ................................................................................................................................. 58display ............................................................................................................................. 58hide ................................................................................................................................... 59layout ............................................................................................................................... 59params ............................................................................................................................... 59sort ................................................................................................................................... 59max_per_page .................................................................................................................. 60pager_class..................................................................................................................... 60batch_actions ................................................................................................................ 60object_actions .............................................................................................................. 60actions ............................................................................................................................. 60peer_method..................................................................................................................... 60table_method .................................................................................................................. 61peer_count_method ........................................................................................................ 61table_count_method...................................................................................................... 61

    Table of Contents v

    ----------------- Brought to you by

  • filter .................................................................................................................... 61display ............................................................................................................................. 58class ................................................................................................................................. 62

    form......................................................................................................................... 62display ............................................................................................................................. 58class ................................................................................................................................. 62

    edit......................................................................................................................... 62title ................................................................................................................................. 58actions ............................................................................................................................. 60

    new........................................................................................................................... 63title ................................................................................................................................. 58actions ............................................................................................................................. 60

    The databases.yml Configuration File ............................................................ 64Propel....................................................................................................................... 65Doctrine ................................................................................................................... 66

    The security.yml Configuration File ............................................................... 68Authentication ......................................................................................................... 68Authorization ........................................................................................................... 69

    The cache.yml Configuration File................................................................... 70enabled .................................................................................................................. 71with_layout .......................................................................................................... 71lifetime ................................................................................................................ 71client_lifetime ................................................................................................. 71contextual ............................................................................................................ 71

    The routing.yml Configuration File ................................................................ 73Route Classes........................................................................................................... 74Route Configuration ................................................................................................ 75class ................................................................................................................................. 75url ..................................................................................................................................... 75params ............................................................................................................................... 75param ................................................................................................................................. 75options ............................................................................................................................. 75requirements .................................................................................................................. 75type ................................................................................................................................... 76

    sfRoute .................................................................................................................. 76sfRequestRoute ................................................................................................... 76sf_method......................................................................................................................... 76

    sfObjectRoute...................................................................................................... 76model ................................................................................................................................. 76type ................................................................................................................................... 76method ............................................................................................................................... 76allow_empty..................................................................................................................... 77convert ............................................................................................................................. 77

    sfPropelRoute...................................................................................................... 77method_for_criteria.................................................................................................... 77

    sfDoctrineRoute ................................................................................................. 77method_for_query .......................................................................................................... 77

    sfRouteCollection ............................................................................................. 77sfObjectRouteCollection................................................................................. 77model ................................................................................................................................. 76actions ............................................................................................................................. 77

    Table of Contents vi

    ----------------- Brought to you by

  • module ............................................................................................................................... 78prefix_path..................................................................................................................... 78column ............................................................................................................................... 78with_show......................................................................................................................... 78segment_names ................................................................................................................ 78model_methods ................................................................................................................ 78requirements .................................................................................................................. 75with_wildcard_routes.................................................................................................. 79route_class..................................................................................................................... 79collection_actions...................................................................................................... 79object_actions .............................................................................................................. 79

    sfPropelRouteCollection................................................................................. 79sfDoctrineRouteCollection ............................................................................ 79

    The app.yml Configuration File ...................................................................... 80The filters.yml Configuration File .................................................................. 81

    Filters....................................................................................................................... 83rendering .............................................................................................................. 83security ................................................................................................................ 83cache ...................................................................................................................... 83execution .............................................................................................................. 84

    The view.yml Configuration File ..................................................................... 85Layout ...................................................................................................................... 85Stylesheets............................................................................................................... 86JavaScripts ............................................................................................................... 86Metas and HTTP Metas ........................................................................................... 87

    Other Configuration Files ............................................................................... 88autoload.yml........................................................................................................ 88config_handlers.yml ......................................................................................... 89core_compile.yml ............................................................................................... 90module.yml ............................................................................................................ 90

    Events.............................................................................................................. 91Usage ....................................................................................................................... 91Event Types ............................................................................................................. 92notify ............................................................................................................................... 92notifyUntil..................................................................................................................... 92filter ............................................................................................................................... 92

    Events ...................................................................................................................... 93application .......................................................................................................... 95application.log ............................................................................................................ 95application.throw_exception ................................................................................... 95

    command .................................................................................................................. 95command.log..................................................................................................................... 95command.pre_command.................................................................................................... 95command.post_command.................................................................................................. 96command.filter_options ............................................................................................. 96

    configuration...................................................................................................... 96configuration.method_not_found ............................................................................ 96

    component .............................................................................................................. 96component.method_not_found ..................................................................................... 96

    context .................................................................................................................. 97

    Table of Contents vii

    ----------------- Brought to you by

  • context.load_factories ............................................................................................. 97controller ............................................................................................................ 97controller.change_action ......................................................................................... 97controller.method_not_found ................................................................................... 97controller.page_not_found ....................................................................................... 97

    form......................................................................................................................... 98form.post_configure.................................................................................................... 98form.filter_values...................................................................................................... 98form.validation_error ............................................................................................... 98form.method_not_found ............................................................................................... 98

    plugin .................................................................................................................... 99plugin.pre_install...................................................................................................... 99plugin.post_install.................................................................................................... 99plugin.pre_uninstall.................................................................................................. 99plugin.post_uninstall ............................................................................................... 99

    request ................................................................................................................ 100request.filter_parameters ..................................................................................... 100request.method_not_found ....................................................................................... 100

    response .............................................................................................................. 100response.method_not_found ..................................................................................... 100response.filter_content ......................................................................................... 100

    routing ................................................................................................................ 101routing.load_configuration ................................................................................... 101

    task....................................................................................................................... 101task.cache.clear ........................................................................................................ 101

    template .............................................................................................................. 101template.filter_parameters ................................................................................... 101

    user....................................................................................................................... 101user.change_culture.................................................................................................. 101user.method_not_found ............................................................................................. 102user.change_authentication ................................................................................... 102

    view....................................................................................................................... 102view.configure_format ............................................................................................. 102view.method_not_found ............................................................................................. 102

    view.cache .......................................................................................................... 103view.cache.filter_content ..................................................................................... 103

    Tasks ............................................................................................................. 104Available Tasks ...................................................................................................... 105help ................................................................................................................................. 107list ................................................................................................................................. 107

    app......................................................................................................................... 107app::routes................................................................................................................... 107

    cache .................................................................................................................... 108cache::clear ................................................................................................................ 108

    configure ............................................................................................................ 108configure::author ...................................................................................................... 108configure::database.................................................................................................. 109

    doctrine .............................................................................................................. 110doctrine::build .......................................................................................................... 110doctrine::build-db.................................................................................................... 111doctrine::build-filters ......................................................................................... 112doctrine::build-forms ............................................................................................. 112doctrine::build-model ............................................................................................. 112

    Table of Contents viii

    ----------------- Brought to you by

  • doctrine::build-schema ........................................................................................... 113doctrine::build-sql.................................................................................................. 113doctrine::clean-model-files ................................................................................. 114doctrine::create-model-tables............................................................................. 114doctrine::data-dump.................................................................................................. 114doctrine::data-load.................................................................................................. 115doctrine::delete-model-files............................................................................... 115doctrine::dql .............................................................................................................. 116doctrine::drop-db ...................................................................................................... 116doctrine::generate-admin ....................................................................................... 117doctrine::generate-migration............................................................................... 118doctrine::generate-migrations-db ...................................................................... 118doctrine::generate-migrations-diff .................................................................. 118doctrine::generate-migrations-models .............................................................. 119doctrine::generate-module ..................................................................................... 119doctrine::generate-module-for-route ................................................................ 120doctrine::insert-sql................................................................................................ 121doctrine::migrate ...................................................................................................... 121

    generate .............................................................................................................. 122generate::app .............................................................................................................. 122generate::module ........................................................................................................ 122generate::project ...................................................................................................... 123generate::task ............................................................................................................ 124

    i18n....................................................................................................................... 125i18n::extract .............................................................................................................. 125i18n::find..................................................................................................................... 125

    log......................................................................................................................... 126log::clear..................................................................................................................... 126log::rotate................................................................................................................... 126

    plugin .................................................................................................................. 127plugin::add-channel.................................................................................................. 127plugin::install .......................................................................................................... 127plugin::list ................................................................................................................ 128plugin::publish-assets ........................................................................................... 128plugin::uninstall ...................................................................................................... 129plugin::upgrade .......................................................................................................... 129

    project ................................................................................................................ 130project::clear-controllers ................................................................................... 130project::deploy .......................................................................................................... 130project::disable ........................................................................................................ 131project::enable .......................................................................................................... 132project::optimize ...................................................................................................... 132project::permissions................................................................................................ 132project::send-emails................................................................................................ 133project::validate ...................................................................................................... 133

    propel .................................................................................................................. 133propel::build .............................................................................................................. 133propel::build-all ...................................................................................................... 135propel::build-all-load ........................................................................................... 135propel::build-filters ............................................................................................. 136propel::build-forms.................................................................................................. 137propel::build-model.................................................................................................. 137propel::build-schema................................................................................................ 138propel::build-sql ...................................................................................................... 138propel::data-dump ...................................................................................................... 138

    Table of Contents ix

    ----------------- Brought to you by

  • propel::data-load ...................................................................................................... 139propel::generate-admin ........................................................................................... 140propel::generate-module ......................................................................................... 141propel::generate-module-for-route .................................................................... 142propel::graphviz ........................................................................................................ 142propel::insert-sql.................................................................................................... 143propel::schema-to-xml ............................................................................................. 143propel::schema-to-yml ............................................................................................. 143

    symfony ................................................................................................................ 144symfony::test .............................................................................................................. 144

    test....................................................................................................................... 144test::all....................................................................................................................... 144test::coverage ............................................................................................................ 145test::functional ........................................................................................................ 145test::unit..................................................................................................................... 146

    Whats new in symfony 1.3/1.4?.................................................................... 149Mailer..................................................................................................................... 149Security.................................................................................................................. 149Widgets .................................................................................................................. 150

    Default Labels................................................................................................................... 150sfWidgetFormInputText ............................................................................................. 150I18n widgets ..................................................................................................................... 150Fluent Interface................................................................................................................ 150

    Validators............................................................................................................... 150sfValidatorRegex ........................................................................................................ 150sfValidatorUrl ............................................................................................................ 151sfValidatorSchemaCompare ....................................................................................... 151sfValidatorChoice, sfValidatorPropelChoice,sfValidatorDoctrineChoice ..................................................................................... 151I18n validators.................................................................................................................. 151Default Error Messages.................................................................................................... 151Fluent Interface................................................................................................................ 150sfValidatorFile .......................................................................................................... 152

    Forms..................................................................................................................... 152sfForm::useFields().................................................................................................. 152sfForm::getEmbeddedForm($name) .......................................................................... 152sfForm::renderHiddenFields()............................................................................... 152sfFormSymfony .............................................................................................................. 153BaseForm ......................................................................................................................... 153sfForm::doBind() ........................................................................................................ 153sfForm(Doctrine|Propel)::doUpdateObject() ................................................... 153sfForm::enableLocalCSRFProtection() andsfForm::disableLocalCSRFProtection() .............................................................. 153Fluent Interface................................................................................................................ 150

    Autoloaders............................................................................................................ 154sfAutoloadAgain (EXPERIMENTAL) ........................................................................... 154

    Tests....................................................................................................................... 154Speed up Testing.............................................................................................................. 154Functional Tests ............................................................................................................... 154JUnit Compatible XML Output ......................................................................................... 155Easy Debugging................................................................................................................ 155Lime Output Colorization ................................................................................................. 155sfTesterResponse::checkForm()............................................................................. 155sfTesterResponse::isValid() ................................................................................. 155

    Table of Contents x

    ----------------- Brought to you by

  • Listen to context.load_factories ............................................................................ 156A better ->click()......................................................................................................... 156

    Tasks...................................................................................................................... 156sfTask::askAndValidate() ....................................................................................... 156symfony:test ................................................................................................................ 156project:deploy ............................................................................................................ 157generate:project ........................................................................................................ 157sfFileSystem::execute() ......................................................................................... 157task.test.filter_test_files ................................................................................. 157Enhancements to sfTask::run().................................................................................. 157sfBaseTask::setConfiguration() .......................................................................... 158project:disable and project:enable..................................................................... 158help and list ................................................................................................................. 158project:optimize ........................................................................................................ 159generate:app ................................................................................................................ 159Sending an Email from a Task.......................................................................................... 159Using the Routing in a Task ............................................................................................. 159

    Exceptions ............................................................................................................. 159Autoloading ...................................................................................................................... 159Web Debug Toolbar.......................................................................................................... 159

    Propel Integration.................................................................................................. 159Propel Behaviors .............................................................................................................. 159propel:insert-sql ...................................................................................................... 159propel:generate-module, propel:generate-admin, propel:generate-admin-for-route....................................................................................................................... 160Propel Behaviors .............................................................................................................. 159Disabling form generation................................................................................................ 160Using a different version of Propel .................................................................................. 160

    Routing .................................................................................................................. 161Default Requirements....................................................................................................... 161sfObjectRouteCollection options............................................................................. 161

    CLI ......................................................................................................................... 161Output Colorization .......................................................................................................... 161

    I18N ....................................................................................................................... 161Data update ...................................................................................................................... 161Sorting according to user locale ...................................................................................... 161

    Plugins ................................................................................................................... 161sfPluginConfiguration::connectTests()............................................................ 162

    Settings.................................................................................................................. 162sf_file_link_format.................................................................................................. 162

    Doctrine Integration .............................................................................................. 163Generating Form Classes ................................................................................................. 163Form Classes Inheritance................................................................................................. 163New Tasks ........................................................................................................................ 163Date Setters and Getters.................................................................................................. 165doctrine:migrate --down ......................................................................................... 165doctrine:migrate --dry-run ................................................................................... 165Output DQL Task as Table of Data ................................................................................... 166Pass query parameters to doctrine:dql ...................................................................... 166Debugging queries in functional tests.............................................................................. 166sfFormFilterDoctrine................................................................................................ 166Configuring Doctrine........................................................................................................ 167doctrine:generate-module, doctrine:generate-admin, doctrine:generate-admin-for-route .......................................................................................................... 168Magic method doc tags .................................................................................................... 168

    Table of Contents xi

    ----------------- Brought to you by

  • Using a different version of Doctrine ............................................................................... 168Web Debug Toolbar ............................................................................................... 168sfWebDebugPanel::setStatus()............................................................................... 168sfWebDebugPanel request parameter ........................................................................... 168

    Partials................................................................................................................... 168Slots improvements .......................................................................................................... 168

    Pagers .................................................................................................................... 169View cache............................................................................................................. 169

    Cache more....................................................................................................................... 169Request .................................................................................................................. 169getContent() ................................................................................................................ 169PUT and DELETE parameters ........................................................................................... 170

    Actions ................................................................................................................... 170redirect()..................................................................................................................... 170

    Helpers .................................................................................................................. 170link_to_if(), link_to_unless()............................................................................. 170

    Context .................................................................................................................. 170Upgrading Projects from 1.2 to 1.3/1.4 ........................................................ 172

    Upgrading to symfony 1.4 ..................................................................................... 172How to upgrade to symfony 1.3? ........................................................................... 173Deprecations.......................................................................................................... 173Autoloading............................................................................................................ 173Routing .................................................................................................................. 174JavaScripts and Stylesheets................................................................................... 174

    Removal of the common filter .......................................................................................... 174Tasks...................................................................................................................... 175

    Formatters........................................................................................................................ 175Escaping ................................................................................................................ 175Doctrine Integration .............................................................................................. 176

    Required Doctrine Version ............................................................................................... 176Admin Generator Delete................................................................................................... 176Override Doctrine Plugin Schema.................................................................................... 176Query logging ................................................................................................................... 176

    Plugins ................................................................................................................... 176Widgets .................................................................................................................. 176Mailer..................................................................................................................... 177YAML ..................................................................................................................... 177Propel..................................................................................................................... 177Tests....................................................................................................................... 178

    Deprecations and removals in 1.3 ................................................................ 179Core Plugins........................................................................................................... 179Methods and Functions ......................................................................................... 179Classes ................................................................................................................... 180Helpers .................................................................................................................. 181Settings.................................................................................................................. 181Tasks...................................................................................................................... 182Miscellaneous ........................................................................................................ 183

    License .......................................................................................................... 184Attribution-Share Alike 3.0 Unported License ...................................................... 184

    Table of Contents xii

    ----------------- Brought to you by

  • About the Author

    Fabien Potencier discovered the Web in 1994, at a time when connecting to the Internetwas still associated with the harmful strident sounds of a modem. Being a developer bypassion, he immediately started to build websites with Perl. But with the release of PHP 5, hedecided to switch focus to PHP, and created the symfony framework project in 2004 to helphis company leverage the power of PHP for its customers.Fabien is a serial-entrepreneur, and among other companies, he created Sensio, a servicesand consulting company specialized in web technologies and Internet marketing, in 1998.Fabien is also the creator of several other Open-Source projects, a writer, a blogger, aspeaker at international conferences, and a happy father of two wonderful kids.His Website: http://fabien.potencier.org/On Twitter: http://www.twitter.com/fabpot

    About the Author xiii

    ----------------- Brought to you by

  • About Sensio Labs

    Sensio Labs is a services and consulting company specialized in Open-Source Webtechnologies and Internet marketing.Founded in 1998 by Fabien Potencier, Gregory Pascal, and Samuel Potencier, Sensiobenefited from the Internet growth of the late 1990s and situated itself as a major player forbuilding complex web applications. It survived the Internet bubble burst by applyingprofessional and industrial methods to a business where most players seemed to reinvent thewheel for each project. Most of Sensios clients are large corporations, who hire its teams todeal with small- to middle-scale projects with strong time-to-market and innovationconstraints.Sensio Labs develops interactive web applications, both for dot-com and traditionalcompanies. Sensio Labs also provides auditing, consulting, and training on Internettechnologies and complex application deployment. It helps define the global Internet strategyof large-scale industrial players. Sensio Labs has projects in France and abroad.For its own needs, Sensio Labs develops the symfony framework and sponsors its deploymentas an Open-Source project. This means that symfony is built from experience and is employedin many web applications, including those of large corporations.Since its beginnings eleven years ago, Sensio has always based its strategy on strongtechnical expertise. The company focuses on Open-Source technologies, and as for dynamicscripting languages, Sensio offers developments in all LAMP platforms. Sensio acquiredstrong experience on the best frameworks using these languages, and often develops webapplications in Django, Rails, and, of course, symfony.Sensio Labs is always open to new business opportunities, so if you ever need help developinga web application, learning symfony, or evaluating a symfony development, feel free tocontact us at [email protected]. The consultants, project managers, webdesigners, and developers of Sensio can handle projects from A to Z.

    About Sensio Labs xiv

    ----------------- Brought to you by

  • Which symfony Version?

    This book has been written for both symfony 1.3 and symfony 1.4. As writing a single book fortwo different versions of a software is quite unusual, this section explains what the maindifferences are between the two versions, and how to make the best choice for your projects.Both the symfony 1.3 and symfony 1.4 versions have been released at about the same time (atthe end of 2009). As a matter of fact, they both have the exact same feature set. The onlydifference between the two versions is how each supports backward compatibility with oldersymfony versions.Symfony 1.3 is the release youll want to use if you need to upgrade a legacy project that usesan older symfony version (1.0, 1.1, or 1.2). It has a backward compatibility layer and all thefeatures that have been deprecated during the 1.3 development period are still available. Itmeans that upgrading is easy, simple, and safe.If you start a new project today, however, you should use symfony 1.4. This version has thesame feature set as symfony 1.3 but all the deprecated features, including the entirecompatibility layer, have been removed. This version is cleaner and also a bit faster thansymfony 1.3. Another big advantage of using symfony 1.4 is its longer support. Being a LongTerm Support release, it will be maintained by the symfony core team for three years (untilNovember 2012).Of course, you can migrate your projects to symfony 1.3 and then slowly update your code toremove the deprecated features and eventually move to symfony 1.4 in order to benefit fromthe long term support. You have plenty of time to plan the move as symfony 1.3 will besupported for a year (until November 2010).As this book does not describe deprecated features, all examples work equally well on bothversions.

    Which symfony Version? xv

    ----------------- Brought to you by

  • Introduction

    Using a full-stack framework like symfony is one of the easiest ways to increase your speedand efficiency as a web developer. The framework comes bundled with many useful featuresthat help you concentrate on your applications business logic rather than on theimplementation on yet another object pager or yet another database abstraction layer.However, this also comes at a cost; learning all the available features and all the built-inconfiguration possibilities does not happen overnight.The Practical Symfony1 book is a great way for a beginner to learn symfony, understand howit works, and also see best web development practices in action.When you begin working on your own projects, you need a reference guide. A book where youcan easily find answers to your questions at your fingertips. The Symfony Reference Guidebook aims to provide such a guide. It acts as a complementary book to Practical symfony. Thisis a book you will keep with you whenever you develop with symfony. This book is the fastestway to find every available configuration thanks to a very detailed table of contents, an indexof terms, cross-references inside the chapters, tables, and much more.Despite being the lead developer of symfony, I still use this book from time to time to look fora particular configuration setting, or just browse the book to re-discover some great tips. Ihope you will enjoy using it on a day to day basis as much as I do.

    1. http://www.symfony-project.org/jobeet/

    Introduction 16

    ----------------- Brought to you by

  • Listing2-1

    Listing2-2

    Listing2-3

    Listing2-4

    Listing2-5

    The YAML Format

    Most configuration files in symfony are in the YAML format. According to the official YAML2website, YAML is a human friendly data serialization standard for all programminglanguages.YAML is a simple language that describes data. Like PHP, it has a syntax for simple types likestrings, booleans, floats, or integers. But unlike PHP, it makes a difference between arrays(sequences) and hashes (mappings).This section describes the minimum set of features you will need to use YAML as aconfiguration file format in symfony, although the YAML format is capable of describing muchmore complex nested data structures.

    ScalarsThe syntax for scalars is similar to the PHP syntax.

    StringsA string in YAML

    'A singled-quoted string in YAML'

    In a single quoted string, a single quote ' must be doubled:

    'A single quote '' in a single-quoted string'

    "A double-quoted string in YAML\n"

    Quoted styles are useful when a string starts or ends with one or more relevant spaces.

    The double-quoted style provides a way to express arbitrary strings, by using \ escapesequences. It is very useful when you need to embed a \n or a unicode character in astring.

    When a string contains line breaks, you can use the literal style, indicated by the pipe (|), toindicate that the string will span several lines. In literals, newlines are preserved:

    2. http://yaml.org/

    The YAML Format 17

    ----------------- Brought to you by

  • Listing2-6

    Listing2-7

    Listing2-8

    Listing2-9

    Listing2-10

    Listing2-11

    Listing2-12

    Listing2-13

    Listing2-14

    |\/ /| |\/| |/ / | | | |__

    Alternatively, strings can be written with the folded style, denoted by >, where each linebreak is replaced by a space:

    >This is a very long sentencethat spans several lines in the YAMLbut which will be rendered as a stringwithout carriage returns.

    Notice the two spaces before each line in the previous examples. They wont appear in theresulting PHP strings.

    Numbers# an integer12

    # an octal014

    # a hexadecimal0xC

    # a float13.4

    # an exponent1.2e+34

    # infinity.inf

    NullsNulls in YAML can be expressed with null or ~.

    BooleansBooleans in YAML are expressed with true and false.

    DatesYAML uses the ISO-8601 standard to express dates:

    2001-12-14t21:59:43.10-05:00

    # simple date2002-12-14

    The YAML Format 18

    ----------------- Brought to you by

  • Listing2-15

    Listing2-16

    Listing2-17

    Listing2-18

    Listing2-19

    Listing2-20

    Listing2-21

    CollectionsA YAML file is rarely used to describe a simple scalar. Most of the time, it describes acollection. A collection can be either a sequence or mapping of elements. Sequences andmappings are both converted to PHP arrays.Sequences use a dash followed by a space (-):

    - PHP- Perl- Python

    This is equivalent to the following PHP code:

    array('PHP', 'Perl', 'Python');

    Mappings use a colon followed by a space (:) to mark each key/value pair:

    PHP: 5.2MySQL: 5.1Apache: 2.2.20

    which is equivalent to the following PHP code:

    array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20');

    In a mapping, a key can be any valid YAML scalar.

    The number of spaces between the colon and the value does not matter, as long as there is atleast one:

    PHP: 5.2MySQL: 5.1Apache: 2.2.20

    YAML uses indentation with one or more spaces to describe nested collections:

    "symfony 1.0":PHP: 5.0Propel: 1.2

    "symfony 1.2":PHP: 5.2Propel: 1.3

    This YAML is equivalent to the following PHP code:

    array('symfony 1.0' => array(

    'PHP' => 5.0,'Propel' => 1.2,

    ),'symfony 1.2' => array(

    'PHP' => 5.2,'Propel' => 1.3,

    The YAML Format 19

    ----------------- Brought to you by

  • Listing2-22

    Listing2-23

    Listing2-24

    Listing2-25

    Listing2-26

    Listing2-27

    Listing2-28

    ),);

    There is one important thing you need to remember when using indentation in a YAML file:Indentation must be done with one or more spaces, but never with tabulations.you can nest sequences and mappings as you like or you can nest sequences and mappingslike so:

    'Chapter 1':- Introduction- Event Types

    'Chapter 2':- Introduction- Helpers

    YAML can also use flow styles for collections, using explicit indicators rather than indentationto denote scope.A sequence can be written as a comma separated list within square brackets ([]):

    [PHP, Perl, Python]

    A mapping can be written as a comma separated list of key/values within curly braces ({}):

    { PHP: 5.2, MySQL: 5.1, Apache: 2.2.20 }

    You can also mix and match styles to achieve better readability:

    'Chapter 1': [Introduction, Event Types]'Chapter 2': [Introduction, Helpers]

    "symfony 1.0": { PHP: 5.0, Propel: 1.2 }"symfony 1.2": { PHP: 5.2, Propel: 1.3 }

    CommentsComments can be added in YAML by prefixing them with a hash mark (#):

    # Comment on a line"symfony 1.0": { PHP: 5.0, Propel: 1.2 } # Comment at the end of a line"symfony 1.2": { PHP: 5.2, Propel: 1.3 }

    Comments are simply ignored by the YAML parser and do not need to be indentedaccording to the current level of nesting in a collection.

    Dynamic YAML filesIn symfony, a YAML file can contain PHP code that is evaluated just before the parsingoccurs:

    1.0:version:

    The YAML Format 20

    ----------------- Brought to you by

  • 1.1:version: ""

    Be careful to not mess up with the indentation. Keep in mind the following simple tips whenadding PHP code to a YAML file:

    The statements must always start the line or be embedded in a value. If a statement ends a line, you need to explicitly output a new line (\n).

    The YAML Format 21

    ----------------- Brought to you by

  • Listing2-29

    A Full Length ExampleThe following example illustrates the YAML syntax explained in this section:

    "symfony 1.0":end_of_maintainance: 2010-01-01is_stable: truerelease_manager: "Gregoire Hubert"description: >

    This stable version is the right choice for projectsthat need to be maintained for a long period of time.

    latest_beta: ~latest_minor: 1.0.20supported_orms: [Propel]archives: { source: [zip, tgz], sandbox: [zip, tgz] }

    "symfony 1.2":end_of_maintainance: 2008-11-01is_stable: truerelease_manager: 'Fabian Lange'description: >

    This stable version is the right choiceif you start a new project today.

    latest_beta: nulllatest_minor: 1.2.5supported_orms:

    - Propel- Doctrine

    archives:source:

    - zip- tgz

    sandbox:- zip- tgz

    The YAML Format 22

    ----------------- Brought to you by

  • Listing3-1

    Listing3-2

    Configuration File Principles

    Symfony configuration files are based on a common set of principles and share some commonproperties. This section describes them in detail, and acts as a reference for other sectionsdescribing YAML configuration files.

    CacheAll configuration files in symfony are cached to PHP files by configuration handler classes.When the is_debug setting is set to false (for instance for the prod environment), theYAML file is only accessed for the very first request; the PHP cache is used for subsequentrequests. This means that the heavy work is done only once, when the YAML file is parsedand interpreted the first time.

    In the dev environment, where is_debug is set to true by default, the compilation is donewhenever the configuration file changes (symfony checks the file modification time).

    The parsing and caching of each configuration file is done by specialized configurationhandler classes, configured in config_handler.yml (page 89).In the following sections, when we talk about the compilation, it means the first time whenthe YAML file is converted to a PHP file and stored in the cache.

    To force the configuration cache to be reloaded, you can use the cache:clear task:

    $ php symfony cache:clear --type=config

    ConstantsConfiguration files: core_compile.yml, factories.yml, generator.yml,databases.yml, filters.yml, view.yml, autoload.ymlSome configuration files allow the usage of pre-defined constants. Constants are declaredwith placeholders using the %XXX% notation (where XXX is an uppercase key) and arereplaced by their actual value at compilation time.

    Configuration SettingsA constant can be any setting defined in the settings.yml configuration file. Theplaceholder key is then an upper-case setting key name prefixed with SF_:

    logging: %SF_LOGGING_ENABLED%

    Configuration File Principles 23

    ----------------- Brought to you by

  • When symfony compiles the configuration file, it replaces all occurrences of the %SF_XXX%placeholders by their value from settings.yml. In the above example, it will replace theSF_LOGGING_ENABLED placeholder with the value of the logging_enabled setting definedin settings.yml.

    Application SettingsYou can also use settings defined in the app.yml configuration file by prefixing the key namewith APP_.

    Special ConstantsBy default, symfony defines four constants according to the current front controller:

    Constant Description Configuration methodSF_APP The current application name getApplication()SF_ENVIRONMENT The current environment name getEnvironment()SF_DEBUG Whether debug is enabled or not isDebug()SF_SYMFONY_LIB_DIR The symfony libraries directory getSymfonyLibDir()

    DirectoriesConstants are also very useful when you need to reference a directory or a file path withouthardcoding it. Symfony defines a number of constants for common project and applicationdirectories.At the root of the hierarchy is the project root directory, SF_ROOT_DIR. All other constantsare derived from this root directory.The project directory structure is defined as follows:

    Constants Default ValueSF_APPS_DIR SF_ROOT_DIR/appsSF_CONFIG_DIR SF_ROOT_DIR/configSF_CACHE_DIR SF_ROOT_DIR/cacheSF_DATA_DIR SF_ROOT_DIR/dataSF_DOC_DIR SF_ROOT_DIR/docSF_LIB_DIR SF_ROOT_DIR/libSF_LOG_DIR SF_ROOT_DIR/logSF_PLUGINS_DIR SF_ROOT_DIR/pluginsSF_TEST_DIR SF_ROOT_DIR/testSF_WEB_DIR SF_ROOT_DIR/webSF_UPLOAD_DIR SF_WEB_DIR/uploads

    The application directory structure is defined under the SF_APPS_DIR/APP_NAME directory:

    Constants Default ValueSF_APP_CONFIG_DIR SF_APP_DIR/configSF_APP_LIB_DIR SF_APP_DIR/lib

    Configuration File Principles 24

    ----------------- Brought to you by

  • Listing3-3

    Constants Default ValueSF_APP_MODULE_DIR SF_APP_DIR/modulesSF_APP_TEMPLATE_DIR SF_APP_DIR/templatesSF_APP_I18N_DIR SF_APP_DIR/i18n

    Eventually, the application cache directory structure is defined as follows:

    Constants Default ValueSF_APP_BASE_CACHE_DIR SF_CACHE_DIR/APP_NAMESF_APP_CACHE_DIR SF_CACHE_DIR/APP_NAME/ENV_NAMESF_TEMPLATE_CACHE_DIR SF_APP_CACHE_DIR/templateSF_I18N_CACHE_DIR SF_APP_CACHE_DIR/i18nSF_CONFIG_CACHE_DIR SF_APP_CACHE_DIR/configSF_TEST_CACHE_DIR SF_APP_CACHE_DIR/testSF_MODULE_CACHE_DIR SF_APP_CACHE_DIR/modules

    environment-awarenessConfiguration files: settings.yml, factories.yml, databases.yml, app.ymlSome symfony configuration files are environment-aware their interpretation depends onthe current symfony environment. These files have different sections that define theconfiguration should vary for each environment. When creating a new application, symfonycreates sensible configuration for the three default symfony environments: prod, test, anddev:

    prod:# Configuration for the `prod` environment

    test:# Configuration for the `test` environment

    dev:# Configuration for the `dev` environment

    all:# Default configuration for all environments

    When symfony needs a value from a configuration file, it merges the configuration found inthe current environment section with the all configuration. The special all sectiondescribes the default configuration for all environments. If the environment section is notdefined, symfony falls back to the all configuration.

    Configuration CascadeConfiguration files: core_compile.yml, autoload.yml, settings.yml, factories.yml,databases.yml, security.yml, cache.yml, app.yml, filters.yml, view.ymlSome configuration files can be defined in several config/ sub-directories contained in theproject directory structure.

    Configuration File Principles 25

    ----------------- Brought to you by

  • When the configuration is compiled, the values from all the different files are mergedaccording to a precedence order:

    The module configuration (PROJECT_ROOT_DIR/apps/APP_NAME/modules/MODULE_NAME/config/XXX.yml)

    The application configuration (PROJECT_ROOT_DIR/apps/APP_NAME/config/XXX.yml)

    The project configuration (PROJECT_ROOT_DIR/config/XXX.yml) The configuration defined in the plugins (PROJECT_ROOT_DIR/plugins/*/

    config/XXX.yml) The default configuration defined in the symfony libraries (SF_LIB_DIR/config/

    XXX.yml)

    For instance, the settings.yml defined in an application directory inherits from theconfiguration set in the main config/ directory of the project, and eventually from thedefault configuration contained in the framework itself (lib/config/config/settings.yml).

    When a configuration file is environment-aware and can be defined in several directories,the following priority list applies:

    1. Module2. Application3. Project4. Specific environment5. All environments6. Default

    Configuration File Principles 26

    ----------------- Brought to you by

  • The settings.yml Configuration File

    Most aspects of symfony can be configured either via a configuration file written in YAML, orwith plain PHP. In this section, the main configuration file for an application, settings.yml,will be described.The main settings.yml configuration file for an application can be found in the apps/APP_NAME/config/ directory.As discussed in the introduction, the settings.yml file is environment-aware (page 25),and benefits from the configuration cascade mechanism (page 25).Each environment section has two sub-sections: .actions and .settings. All configurationdirectives go under the .settings sub-section, except for the default actions to be renderedfor some common pages.

    The settings.yml configuration file is cached as a PHP file; the process is automaticallymanaged by the sfDefineEnvironmentConfigHandler class (page 89).

    The settings.yml Configuration File 27

    ----------------- Brought to you by

  • Settings .actions

    error_404 (page 29) login (page 29) secure (page 29) module_disabled (page 29)

    .settings

    cache (page 31) charset (page 30) check_lock (page 33) compressed (page 33) csrf_secret (page 30) default_culture (page 32) default_timezone (page 31) enabled_modules (page 30) error_reporting (page 33) escaping_strategy (page 29) escaping_method (page 30) etag (page 31) i18n (page 31) lazy_cache_key (page 32) file_link_format (page 32) logging_enabled (page 32) no_script_name (page 32) standard_helpers (page 32) use_database (page 33) web_debug (page 33) web_debug_web_dir (page 34)

    The settings.yml Configuration File 28

    ----------------- Brought to you by

  • Listing4-1

    Listing4-2

    The .actions Sub-SectionDefault configuration:

    default:.actions:

    error_404_module: defaulterror_404_action: error404

    login_module: defaultlogin_action: login

    secure_module: defaultsecure_action: secure

    module_disabled_module: defaultmodule_disabled_action: disabled

    The .actions sub-section defines the action to execute when common pages must berendered. Each definition has two components: one for the module (suffixed by _module),and one for the action (suffixed by _action).

    error_404

    The error_404 action is executed when a 404 page must be rendered.

    login

    The login action is executed when a non-authenticated user tries to access a secure page.

    secure

    The secure action is executed when a user doesnt have the required credentials.

    module_disabled

    The module_disabled action is executed when a user requests a disabled module.

    The .settings Sub-SectionThe .settings sub-section is where the framework configuration occurs. The paragraphsbelow describe all possible settings and are roughly ordered by importance.All settings defined in the .settings section are available anywhere in the code by using thesfConfig object and prefixing the setting with sf_. For instance, to get the value of thecharset setting, use:

    sfConfig::get('sf_charset');

    escaping_strategy

    Default: true

    The settings.yml Configuration File 29

    ----------------- Brought to you by

  • The escaping_strategy setting is a Boolean setting that determines if the output escapersub-framework is enabled. When enabled, all variables made available in the templates areautomatically escaped by calling the helper function defined by the escaping_methodsetting (see below).Be careful that the escaping_method is the default helper used by symfony, but this can beoverridden on a case by case basis, when outputting a variable in a JavaScript script tag forexample.The output escaper sub-framework uses the charset setting for the escaping.It is highly recommended to leave the default value to true.

    This settings can be set when you create an application with the generate:app task byusing the --escaping-strategy option.

    escaping_method

    Default: ESC_SPECIALCHARSThe escaping_method defines the default function to use for escaping variables intemplates (see the escaping_strategy setting above).You can choose one of the built-in values: ESC_SPECIALCHARS, ESC_RAW, ESC_ENTITIES,ESC_JS, ESC_JS_NO_ENTITIES, and ESC_SPECIALCHARS, or create your own function.Most of the time, the default va


Recommended