Configuration in practice
Overview
The configuration can be defined at several levels : project, application, module. It can also be defined for several environments : development, test, production, and any additional environment needed. By modifying YAML files, you get the power of configuration at your fingertips.
Introduction
The symfony configuration system is inspired by the way Mojavi handles configuration. Although not appreciated by everyone, this system is extremely powerful.
Configuration is distributed into files, by subject. The files contain parameter definitions, or settings.
The parameters can be set in a cascade of definitions. For instance, a given parameter can be defined at the project level, redefined at the application level, and further redefined at the module level. But this cascading also applies to environments. A parameter definition in a named environment has precedence over the same parameter definition for all environments, which has precedence over a definition in the default configuration.
Note: Environment-dependent configuration files will be identified by a star * in this documentation.
Project configuration
There are a few project configuration files by default. Here are the files that can be found in the myproject/config/ directory:
apache.conf: This file is not really a configuration file, since it is not used by the project. It is given as an example of an Apache configuration for a typical symfony project.
config.php: Contains the path to the symfony libraries. Can hold general project configuration. If you add some define statements in this file, the constants will be accessible from every application of the project. This file is empty by default. see more below
properties.ini: Holds a few parameters used by the pakefile (including the project name)
rsync_exclude.txt: this file specifies which directories have to be excluded from the synchronization between environments. The default content should illustrate its use very well:
stats
.svn
web/uploads
cache
log
web/index.php
config
schema.yml and propel.ini are data access configuration files used by Propel (symfony's ORM layer). They are used to plug the Propel libraries with the symfony classes and the data of your project. The schema.yml contains a representation of the project's relational data model. The propel.ini is automatically generated, so you probably do not need to modify it. If you don't use Propel, these files are not needed.
Application configuration
The principal part of the configuration is the application configuration. The files located in myproject/apps/myapp/config/ will be briefly described here before a deeper look at how to modify them.
Overview
app.yml*: This file should contain the application-specific configuration, i.e. global variables that don't really need to be stored in a database. VAT rates, shipping fares, email addresses are often stored in this file. It is empty by default. See more in the configuration chapter.
config.php: This file bootstraps the application, which means that it does all the very basic initializations to allow the application to start. It normally defines the directory layout (by including the constants.php file), includes the project configuration (myproject/config/config.php), loads the necessary symfony classes, and includes some of the parsed .yml files of the application configuration (the others are loaded on demand). This configuration file is written in PHP rather than YAML because the YAML interpreter isn't loaded when config.php is processed.
databases.yml*: This is where you define the access and the connection settings to the database (host, login, password, database name). see more below
factories.yml*: By default, the symfony framework uses some specific classes for its operation; this file allows you to override this behavior by pointing to alternate classes to manage sessions, actions, front web controller, etc... You normally wouldn't change the content of this file, as will be explained a little further. see more below
filters.yml: Symfony allows the execution of filters before actions. For instance, the Security filter is configured by default to check credentials for restricted actions. If you need to add a custom filter, for instance to calculate the time to execute an action, this is the file that you need to modify.
logging.yml*: Defines which level of detail has to be recorded in the logs, to help you supervise and debug your application. See below for more details. see more below
routing.yml: The routing rules, that allow transforming unreadable and unbookmarkable URLs into "smart" and explicit ones, are stored in this file. For new applications, a few default rules exist. See more in the routing chapter.
settings.yml*: The main settings of a symfony application are defined in this file. This is where you specify if your application has internationalization, its default language, the request timeout, whether caching is turned on or not, and whether routing is turned on. With a one line change in this file, you can shut down the application so you can perform maintenance or upgrade one of its components. This is a perfect example of the benefit of using a single front web controller. see more below
view.yml: The structure of the default View (name of the layout, title and metas, default .js and .css files to be included, name of the included slots, etc.) is set in this file. These settings can be overridden for each module. This file also defines the default value of the meta and title tags. see more below
settings.yml: General settings
The settings.yml file, which is environment dependent, contains the main application configuration. Here is the beginning of its default content:
prod:
dev:
.settings:
# E_ALL | E_STRICT = 4095
error_reporting: 4095
web_debug: on
cache: off
stats: off
no_script_name: off
test:
.settings:
cache: off
stats: off
web_debug: off
all:
# .actions:
# default_module: default
# default_action: index
#
# error_404_module: default
# error_404_action: error404
#
# login_module: default
# login_action: login
#
# module_disabled_module: default
# module_disabled_action: disabled
#
# secure_module: default
# secure_action: secure
#
# unavailable_module: default
# unavailable_action: unavailable
#
# .settings:
# available: on
# module_accessor: module
# action_accessor: action
# content_type: html
...
First of all, you may notice that most of the configuration is inherited from the default definition (the statements starting with a # in the configuration for all environments are comments) It means that, for these parameters, the default configuration is used instead. If you need to override any of them, just remove the comment # marker at the beginning of the appropriate line and change the value.
The parameters defined in the .action category identify the modules and actions to be used under certain circumstances. In particular:
default_*: Specifies which action of which module has to be called when not specified in the URL. This is especially useful to set the home page action of your website (the one that will be called with the relative URL '/')
error_404_*: Specifies the default module/action to be called when a 404 error (page not found) occurs. It defaults to default/error404. This action is not explicit in a new application, but you can override it or choose a completely different module/action
login_*: When a secure page requiring credentials is accessed by an anonymous user, the user will be automatically redirected to a login page. This parameter defines the module/action to use for login purposes.
Here is a list of some of the useful .settings parameters:
available: When set to off, it shuts down the whole application. The user will see a Application temporarily unavailable for maintenance type of message
use_database: If your application doesn't use a database, this parameter should be set to off
use_security: If your application has restricted areas, authentication and credentials, set this parameter to on (see the security chapter for more details)
compressed: Activates the HTML compression to reduce bandwidth requirements and improve performance
i18n: Must be set to on for sites/applications available in multiple languages
default_culture: Specifies the default parameter used to format dates, numbers, currencies (en in the default configuration)
web_debug: Activation of the web debug frame, a tool that gives access to debug info on every page. The quantity of logged information is relative to the entries set in the logging.yml file, and it requires that the SF_DEBUG constant be set to true in the front controller. See more in the debug chapter.
cache: Activates the caching feature to speed up page generation by recording chunks of compiled code
routing: Activates the routing feature to transform the outputted URLs and allow "smart" URLs to be interpreted. See more in the routing chapter.
stats: Activates the recording of statistics for the application
Remember that each one of these settings is accessible from inside the PHP code via the sfConfig class, as explained in the configuration chapter. The parameter name is the setting name prefixed with sf_. For instance, if you want the value of the cache parameter, you just need to call sfConfig::get('sf_cache').
databases.yml: Database settings
If the application/site uses a database, you have to configure the database access by entering a set of parameters in the databases.yml file.
all:
propel:
class: sfPropelDatabase
param:
datasource: symfony
dsn: mysql://root:@oxyscrip.ipowermysql.com/mydatabase
The above example is a shorthand syntax for the setting of all the data access parameters, the long form is shown below:
all:
propel:
class: sfPropelDatabase
param:
datasource: symfony
phptype: mysql
hostspec: oxyscrip.ipowermysql.com
database: mydatabase
username: root
password:
To learn more about data binding and the access to a database, go to the data access chapter.
Note: If your application doesn't use a database, you can improve its performance by setting use_database to off in the settings.yml.
logging.yml: Logging settings
Symfony offers two ways to watch the log messages.
Classically, the logs are written in files. Symfony stores message logs in files according to the application and the environment. For instance, in the myproject/log/ directory, you will probably find two files:
myapp_dev.log
myapp_prod.log
Don't forget to periodically rotate these files, since symfony will not do it automatically.
If the web_debug feature is set to on for your application (in settings.yml), the logs for each request are also available in the browser, in a special layer that appears on the right of the screen. Note that this option is activated by default in the development environment. Refer to the debug chapter for more information.
The logging.yml file defines the level of log messages recorded. By default, all levels are included (from alerts to unrecoverable errors). In the production environment, only the errors are logged.
prod:
level: err
dev:
test:
all:
# active: on
# level: debug
factories.yml: Factories settings
Symfony uses classes such as sfFrontWebController, sfRequest, sfUser, that are part of the framework. In the myproject/apps/myapp/lib/ directory, you can override them with your own myFrontWebController, myRequest classes (myUser already exists). They simply need inherit of the 'sf-' classes, and this allows you to customize their behavior. Teel the framework to use the 'my-' classes instead of the 'sf-' ones by changing the settings found in the factories.yml file:
...
all:
# controller:
# class: sfFrontWebController
#
# request:
# class: sfWebRequest
#
# user:
# class: myUser
...
Have a look at the existing myUser class to see how the inheritance allows for extension and overriding of factories classes.
Front controller configuration
The very first application configuration is actually found in the front controller. Take a look at this default web/index.php:
<?php
define('SF_ROOT_DIR', dirname(__FILE__).'/..');
define('SF_APP', 'fo');
define('SF_ENVIRONMENT', 'prod');
define('SF_DEBUG', true);
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
sfContext::getInstance()->getController()->dispatch();
?>
After defining the name of the application (fo) and the environment (prod), the general configuration file is called before the dispatching. So a few useful constants are defined here:
SF_ROOT_DIR: Project root path (normally, should remain at its defaults value dirname(__FILE__).'/..')
SF_APP: Application name in the project
SF_ENVIRONMENT: Environment name (prod, dev or any other project-specific environment that you define)
SF_DEBUG: Activation of the debug mode
If you need to change one of these values, you probably need an additional front controller. The controller chapter will tell you more about it.
Additional application configuration
A second set of configuration files is in the symfony installation directory; the settings defined there are default settings that seldom need to be modified, or that are global to all projects. However, if you need to modify them, just copy the required file from the $pear_data_dir/symfony/config/ directory to your myproject/apps/myapp/config/ directory. The settings defined in an application always have precedence.
autoload.yml: Settings of the autoloading feature. This feature exempts you from requiring custom classes in your code if they are located in specific directories. see more below
constants.php: Overrides the default application file structure. see more below
core_compile.yml and bootstrap_compile.yml are lists of classes to be included to start an application (in bootstrap_compile.yml) and to process a request (in core_compile.yml). These classes are actually concatenated into an optimized PHP file without comments, which will accelerate the execution by minimizing the file access operations (1 file is loaded instead of more than 40 for each request). This is specially useful if you don't use a PHP accelerator.
config_handlers.yml: Do you remember about configuration handlers? This is where you can add or modify the handlers used to process each configuration file, for instance to use the less flexible INI or XML files instead of the more efficient YAML files. Each configuration file having a handler class definition, you will find the customization quite straight forward.
php.yml: Checks that the variables of the php.ini file are properly defined, and allows you to override them if necessary. see more below
autoload.yml: Autoloading settings
When the PHP parser encounters a new myClass statement in the code of an application, it looks for a 'myClass.class.php' file in the paths defined in the autoload.yml. If the file is found, the framework loads the required library and includes it automatically.
In other words, the autoloading feature exempts you from requiring custom classes in your code, provided that they are located in a directory defined in the autoload.yml. This means that you don't need to require libraries at the top of your classes, just let the framework do the job for you, and it will load only the necessary classes and at the appropriate time.
By default, the autoloading works for classes that are located in the following directories:
myproject/lib/,
myproject/lib/model,
myproject/apps/myapp/lib/ and
myproject/apps/myapp/modules/mymodule/lib.
Here is an extract of the default autoload.yml (found in $pear_data_dir/symfony/config/autoload.yml):
autoload:
symfony_core:
name: symfony core classes
ext: .class.php
path: %SF_SYMFONY_LIB_DIR%/symfony
recursive: on
symfony_orm:
name: symfony orm classes
files:
Propel: %SF_SYMFONY_LIB_DIR%/symfony/addon/propel/sfPropelAutoload.php
Criteria: %SF_SYMFONY_LIB_DIR%/propel/util/Criteria.php
SQLException: %SF_SYMFONY_LIB_DIR%/creole/SQLException.php
DatabaseMap: %SF_SYMFONY_LIB_DIR%/propel/map/DatabaseMap.php
project:
name: project classes
ext: .class.php
path: %SF_LIB_DIR%
recursive: on
exclude: [model, plugins]
...
Each autoloading rule has a label, both for visual organization and ability to override it.
If you want to autoload classes stored somewhere else in your file structure, you need to create a new autoload.yml in your myproject/apps/myapp/config/ folder and edit it. You can either override existing rules or add new ones. The custom extension chapter will tell you more about it.
php.yml: PHP configuration
In order to have a php environment compatible with the rules and best practices of agile development, symfony checks and overrides a few settings of the php.ini configuration. This is what the php.yml file is used for. Here is the default php.yml (found in $pear_data_dir/symfony/config/):
set:
magic_quotes_runtime: off
log_errors: on
arg_separator.output: \&
check:
magic_quotes_gpc: off
register_globals: off
The variables defined under the set category are modified (despite how they were defined in the php.ini). The variables defined under the check category cannot be modified on the fly, so their values are checked and an exception raised if your current configuration doesn't match these criterias.
For instance, the default php.yml sets the log_errors to on so that you can trace errors in symfony projects. It also recommends the register_globals to be set to off to prevent security breaches.
If you don't want symfony to apply these settings, or if you want to run a project with magic_quotes_gpc and register_globals set to on (wich we strongly advise against), copy the default php.yml into your application config directory, and change the values to be set or checked. Alternatively, you can delete the lines that are not compatible with your environment in the application copy of the file.
Module configuration
By default, a module has no specific configuration. But, according to your requirements, you can override some application level settings for a given module, or add new parameters restricted to a specific module.
As you may have guessed, module configuration files have to be located in a myproject/apps/myapp/modules/mymodule/config/ directory. These files are:
generator.yml: To create a data access interface (useful for back-office generation) see more below
module.yml*: Custom parameters specific to a module. see more below
security.yml: Access restrictions for actions. see more below
view.yml: Configuration for the views of one or all of the actions of a module. see more below
- data validation files: Although located in the
validate/ directory instead of the config/ one, the YAML data validation files, used to control the data entered in forms, are also specific to a module. see more below
Most module configuration files offer the ability to define parameters for all the views or all the actions of a module, or for a subset of them.
module.yml: Custom module parameters
Modules can have their own settings. In such cases, these settings are defined in a module.yml file. For instance, a 'poll' module might need a max_votes parameter:
all:
.settings:
max_votes: 150
As mentioned in the configuration chapter, the parameter is accessible from the code with the following call:
$max_votes_parameter = sfConfig::get('mod_max_votes');
But maybe you need a totally specific configuration file. In such cases, as in the case of custom app configuration, create a myconfig.yml file together with a config_handlers.yml file to handle its data (read the configuration chapter for more information).
security.yml: Access restriction configuration
To restrict access to an action to a subset of authenticated users having specific credentials, you need to add a module configuration file called security.yml.
Here is an example module security configuration file:
update:
is_secure: on
save:
is_secure: on
orders:
is_secure: on
all:
is_secure: off
credential: customer
The update, save and orders actions of this module will only work for authenticated users with the customer credential.
To learn more about security and the way to set credentials, review the security chapter.
generator.yml: generated module configuration
One commonly used module configuration file is the generator.yml file. When you setup a 'Create Read Update Delete' (CRUD) basic layout for a data object, the module created will have a generator.yml file that you can modify. Read more about CRUDs, scaffolding and generated administrations in the scaffolding chapter.
validate.yml: Form validation
The last common module configuration file relates to form validation. It is not located in the myproject/apps/myapp/modules/mymodule/config/ directory but in the myproject/apps/myapp/modules/mymodule/validate/ directory. YAML validation files look like the following:
methods:
get: [new_email, new_password, new_password2]
post: [new_email, new_password, new_password2]
names:
new_email:
required: Yes
required_msg: Please enter an email address
validators: emailValidator
new_password:
required: Yes
required_msg: Please enter a password
validators: passwordValidator
new_password2:
required: Yes
required_msg: Please confirm your password
passwordValidator:
class: sfStringValidator
param:
min: 4
min_error: Your password needs at least 4 characters
max: 12
max_error: Your password can not have more than 12 characters
emailValidator:
class: sfEmailValidator
param:
email_error: The email you entered is not valid
For more information about form validation and the use of the validation configuration files, review the form validation chapter.
Multiple level configuration
view.yml: View configuration
The rules and parameters governing the View (interface components, layout, headers, etc.) are set in the view.yml configuration file. The file exists by default in the application configuration directory (myproject/apps/myapp/config/), and these settings can be overridden at the module level by adding a view.yml file to a myproject/apps/myapp/modules/mymodule/config/ directory.
Refer to the chapter describing the view configuration to learn more about this feature.
Here is an example module view configuration file:
indexSuccess:
javascripts: [myinteraction]
indexError:
title: Sorry, but there is an error
layout: error
stylesheets: [error]
listSuccess:
template: listtemplate
components:
breadcrumb: []
all:
layout: mylayout
components:
navigation: [bar, navigation]
breadcrumb: [bar, breadcrumb]
The default layout for all the actions of this example module is set to mylayout.php (as opposed to the default layout for the whole application, called layout.php by convention). The navigation and breadcrumb components slots are defined for all the actions of the module, except for the action list where the breadcrumb component slot is suppressed. For this action, the template to be used will not be listSuccess.php but listtemplate.php. If the result of the index action is sfView::ERROR, the template indexError.php will be integrated into the error.php layout, including a special error.css stylesheet and a custom page title. In addition, the index action requires a special javascript called myinteraction.js to be included in the page header so that the template can work correctly.
File structure settings
The project config.php stores the absolute path to the symfony libraries:
<?php
// symfony directories
$sf_symfony_lib_dir = '/usr/lib/php/symfony';
$sf_symfony_data_dir = '/usr/lib/php/data/symfony';
If you don't want to hardcode paths because the project is used in more than one server, you can put the symfony lib/ and data/ directories in your project's lib/symfony/ and data/symfony/ direcories (by using a symbolic link or a svn:externals) and then change your config.php to:
<?php
// symfony directories
$sf_symfony_lib_dir = dirname(__FILE__).'/../lib/symfony';
$sf_symfony_data_dir = dirname(__FILE__).'/../data/symfony';
The application config.php file is often used to customize the directory layout, the directory separator, and everything that the framework needs to find your actions (normally in actions), your modules (normally in modules), your libraries (normally in lib), etc.
Every path to a key directory is determined by a parameter ending with _dir. Here is an extract of the standard file structure configuration (located in $pear_data_dir/symfony/config/constants.php):
...
sfConfig::add(array(
// root directory structure
'sf_cache_dir_name' => 'cache',
'sf_log_dir_name' => 'log',
'sf_lib_dir_name' => 'lib',
'sf_model_dir_name' => 'model',
'sf_web_dir_name' => 'web',
'sf_data_dir_name' => 'data',
'sf_config_dir_name' => 'config',
'sf_apps_dir_name' => 'apps',
// global directory structure
'sf_app_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.$sf_app,
'sf_model_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'model',
'sf_lib_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'lib',
'sf_web_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'web',
'sf_upload_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'web'.DIRECTORY_SEPARATOR.'uploads',
'sf_base_cache_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.$sf_app,
'sf_cache_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.$sf_app.DIRECTORY_SEPARATOR.$sf_environment,
'sf_log_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'log',
'sf_data_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'data',
'sf_config_dir' => $sf_root_dir.DIRECTORY_SEPARATOR.'config',
...
To learn more about the default tree structure, refer to the file structure chapter.
You will probably need to modify this file if you develop an application for a client who already has a defined directory structure and who is not willing to change it to comply with the symfony logic (how could that be possible ?).
Projects inherit their file structure from the framework constants.php. This means that if you need to change the file structure of your project or application, you have to override the settings of the constants.php. This can be done in the application config.php. Beware that it is not empty, so if you need to include file structure definitions there, do it just after the inclusion of the project configuration.
Browsing your own YAML file
Whether you want to create a new config handler, or to read a YAML file directly, you can use the sfYaml class. It is a YAML parser that can turn a YAML file into an associative array:
$myarray = sfYaml::load('/tmp/myfile.yml');
|