Configuration
An overview of all configuration options in the Nette Framework.
Nette application is easily configured using configuration files. They are usually written in NEON format. We recommend to use editors with support for this format for editing.
If you use a string that starts with @
or has %
anywhere in it, you need to escape it by adding
another @
or %
.
application: Application
constants: Defines PHP constants
database: Database
decorator: Decorator
di: DI Container
extensions: Install additional DI extensions
forms: Forms
http: HTTP Headers
includes: Including files
latte: Latte
mail: Mailing
parameters: Parameters
php: PHP configuration options
routing: Routing
search: Automatic service registration
security: Access Control
services: Services
session: Session
tracy: Tracy Debugger
Application
Basic settings for Nette Application.
application:
# shows "Nette Application" panel in Tracy BlueScreen?
debugger: ... # (bool) defaults to true
# will error-presenter be called on error?
catchExceptions: ... # (bool) defaults to true in production mode
# name of error-presenter
errorPresenter: Error # (string) defaults to 'Nette:Error'
# do bad links generate warnings?
# has effect only in developer mode
silentLinks: ... # (bool) defaults to false
Because error-presenters are not called by default in development mode and the errors are displayed by Tracy, changing the
value catchExceptions
to true
helps to verify that error-presenters works correct during
development.
Option silentLinks
determines how Nette behaves in developer mode when link generation fails (for example, because
there is no presenter, etc). The default value false
means that Nette triggers E_USER_WARNING
. Setting
to true
suppresses this error message. In a production environment, E_USER_WARNING
is always invoked. We
can also influence this behavior by setting the presenter variable $invalidLinkMode.
Mapping
Defines the rules according to which the name of the class (for example App\Presenters\HomepagePresenter
) is
derived from the name of the presenter (for example Homepage
). This the mapping can be achieved with the following
configuration:
application:
mapping:
*: App\Presenters\*Presenter
The presenter name is replaced with an asterisk and the result is the class name. Easy!
If we divide presenters into modules, we can have our own mapping for each module:
application:
mapping:
Front: App\FrontModule\*Presenter
Admin: App\AdminModule\*Presenter
Error: App\Error\*Presenter
Now presenter Front:Homepage
maps to class App\FrontModule\HomepagePresenter
and presenter
Admin:Dashboard
to class App\AdminModule\DashboardPresenter
.
It will be more handy to create a general (asterisk) rule that will replace the first two rules and add an extra asterisk just for the module:
application:
mapping:
*: App\*Module\*Presenter
Error: App\ModuleError\*Presenter
Again, the presenter Front:Homepage
maps to the class App\FrontModule\HomepagePresenter
.
But what if we use nested modules and have a presenter Admin:User:Edit
? In this case, the segment with an asterisk
representing the module for each level is simply repeated and the result is class
App\AdminModule\UserModule\EditPresenter
.
An alternative notation is to use an array consisting of three segments instead of a string:
application:
mapping:
*: [App, *Module, *Presenter]
Even in this case, the result will be class App\AdminModule\UserModule\EditPresenter
.
The default value is *: *Module\*Presenter
.
Automatic Registration of Presenters
Nette automatically adds presenters as services to the DI container, which significantly speeds up their creation. How Nette finds out presenters can be configured:
application:
# to look for presenters in Composer class map?
scanComposer: ... # (bool) defaults to true
# a mask that must match the class and file name
scanFilter: ... # (string) defaults to '*Presenter'
# in which directories to look for presenters?
scanDirs: # (string[]|false) defaults to '%appDir%'
- %vendorDir%/mymodule
The directories listed in scanDirs
do not override the default value %appDir%
, but complement it, so
scanDirs
will contain both paths %appDir%
and %vendorDir%/mymodule
. If we want to overwrite
the default directory, we use exclamation mark:
application:
scanDirs!:
- %vendorDir%/mymodule
Directory scanning can be turned off by setting false. We do not recommend completely suppressing the automatic addition of presenters, otherwise application performance will be reduced.
Constants
Creating PHP constants.
constants:
FOOBAR: 'baz'
The FOOBAR
constant will created after startup.
Database
The configuration for one or more database connections for Nette Database.
database:
# DSN, only mandatory key
dsn: "sqlite:%appDir%/Model/demo.db"
user: ...
password: ...
It creates services of type Nette\Database\Connection
and also Nette\Database\Explorer
for the Database Explorer layer. The database connection is usually passed by autowiring, if this is
not possible, use the service names @database.default.connection
resp. @database.default.context
.
Other settings:
database:
# shows database panel in Tracy Bar?
debugger: ... # (bool) defaults to true
# shows query EXPLAIN in Tracy Bar?
explain: ... # (bool) defaults to true
# to enable autowiring for this connection?
autowired: ... # (bool) defaults to true for first connection
# table conventions: discovered, static, or class name
conventions: discovered # (string) defaults to 'discovered'
options:
# to connect to the database only when needed?
lazy: ... # (bool) defaults to false
# PHP database driver class
driverClass: # (string)
# you can list the options found in the PDO driver documentation
PDO::MYSQL_ATTR_COMPRESS: true
In the configuration we can define more database connections by dividing them into named sections:
database:
main:
dsn: 'mysql:host=127.0.0.1;dbname=test'
user: root
password: password
another:
dsn: 'sqlite::memory:'
Each defined connection creates services that includes section name in their name, ie @database.main.connection
& @database.main.context
and further @database.another.connection
&
@database.another.context
.
Autowiring is enabled only for services from the first section. This can be changed with autowired: false
or
autowired: true
. Non-autowired services are passed by name:
services:
- UserManager(@database.another.connection)
Decorator
How to bulk edit all services of a certain type? Need to call a certain method for all presenters inheriting from a particular common ancestor? That's where the decorator comes from.
decorator:
# for all services that are instances of this class or interface
App\Presenters\BasePresenter:
setup:
- setProjectId(10) # call this method
- $absoluteUrls = true # and set the variable
Decorator can also be used to set tags or turn on inject mode.
decorator:
InjectableInterface:
tags: [mytag: 1]
inject: true
DI
Technical settings of the DI container.
di:
# shows DIC in Tracy Bar?
debugger: ... # (bool) defaults to true
# parameter types that you never autowire
excluded: ... # (string[])
# the class from which the DI container inherits
parentClass: ... # (string) defaults to Nette\DI\Container
A big part of the DI container class is metadata. You can shrink this class by disabling parameter passing if you're not using
$container->parameters
, tag passing, not calling $container->findByTag()
, and significantly reduce
metadata for autowiring by listing the classes you use as parameters for method $container->getByType()
.
Example:
di:
export:
# to export parameters?
parameters: false # (bool) defaults to true
# export tags and which ones?
tags: false # (string[]|bool) the default is all
# export data for autowiring and which?
types: # (string[]|bool) the default is all
- Nette\Database\Connection
- Nette\Application\Application
Extensions
Registration of other DI extensions. In this way we add, for exammple, DI extension
Dibi\Bridges\Nette\DibiExtension22
under the name dibi
:
extensions:
dibi: Dibi\Bridges\Nette\DibiExtension22
Then we configure it in it's section called also dibi
:
dibi:
host: localhost
You can also add a extension class with parameters:
extensions:
application: Nette\Bridges\ApplicationDI\ApplicationExtension(%debugMode%, %appDir%, %tempDir%/cache)
Forms
You can change the default form error messages in the configuration.
forms:
messages:
EQUAL: 'Please enter %s.'
NOT_EQUAL: 'This value should not be %s.'
FILLED: 'This field is required.'
BLANK: 'This field should be blank.'
MIN_LENGTH: 'Please enter at least %d characters.'
MAX_LENGTH: 'Please enter no more than %d characters.'
LENGTH: 'Please enter a value between %d and %d characters long.'
EMAIL: 'Please enter a valid email address.'
URL: 'Please enter a valid URL.'
INTEGER: 'Please enter a valid integer.'
FLOAT: 'Please enter a valid number.'
MIN: 'Please enter a value greater than or equal to %d.'
MAX: 'Please enter a value less than or equal to %d.'
RANGE: 'Please enter a value between %d and %d.'
MAX_FILE_SIZE: 'The size of the uploaded file can be up to %d bytes.'
MAX_POST_SIZE: 'The uploaded data exceeds the limit of %d bytes.'
MIME_TYPE: 'The uploaded file is not in the expected format.'
IMAGE: 'The uploaded file must be image in format JPEG, GIF, PNG or WebP.'
Nette\Forms\Controls\SelectBox::VALID: 'Please select a valid option.'
Nette\Forms\Controls\UploadControl::VALID: 'An error occurred during file upload.'
Nette\Forms\Controls\CsrfProtection::PROTECTION: 'Your session has expired. Please return to the home page and try again.'
HTTP headers
http:
# headers that are sent with each request
headers:
X-Powered-By: MyCMS
X-Content-Type-Options: nosniff
X-XSS-Protection: '1; mode=block'
# affects header X-Frame-Options
frames: ... # (string|bool) defaults to 'SAMEORIGIN'
For security reasons, the framework sends a header X-Frame-Options: SAMEORIGIN
, which says that a page can be
displayed inside another page (in element <iframe>
) only if it is on the same domain. This can be unwanted in
certain situations (for example, if you are developing a Facebook application), so the behavior can be changed by setting
frames: http://allowed-host.com
or frames: true
.
Headers Content-Security-Policy
(hereinafter referred to as CSP) can be easily assembled, their description can be
found in CSP description. CSP directives (such as script-src
) can
be written either as strings according to specification or as arrays of values for better readability. Then there is no need
to write quotation marks around keywords such as 'self'
. Nette will also automatically generate a value of
nonce
, so 'nonce-y4PopTLM=='
will be send in the header.
http:
# Content Security Policy
csp:
# string according to CSP specification
default-src: "'self' https://example.com"
# array of values
script-src:
- nonce
- strict-dynamic
- self
- https://example.com
# bool in the case of switches
upgrade-insecure-requests: true
block-all-mixed-content: false
Use <script n:nonce>...</script>
in the templates and the nonce value will be filled in automatically.
Making secure websites in Nette is really easy.
Similarly, headers Content-Security-Policy-Report-Only
(which can be used in parallel with CSP) and Feature Policy can be added:
http:
# Content Security Policy Report-Only
cspReportOnly:
default-src: self
report-uri: 'https://my-report-uri-endpoint'
# Feature Policy
featurePolicy:
unsized-media: none
geolocation:
- self
- https://example.com
HTTP cookie
You can change the default values of some parameters of the Nette\Http\Response::setCookie() and session methods.
http:
# cookie scope by path
cookiePath: ... # (string) defaults to '/'
# which hosts are allowed to receive the cookie
cookieDomain: 'example.com' # (string|domain) defaults to unset
# to send cookies only via HTTPS?
cookieSecure: ... # (bool|auto) defaults to auto
The cookieDomain
option determines which domains (origins) can accept cookies. If not specified, the cookie is
accepted by the same (sub)domain as is set by it, excluding their subdomains. If cookieDomain
is specified,
then subdomains are also included. Therefore, specifying cookieDomain
is less restrictive than omitting.
For example, if cookieDomain: nette.org
is set, cookie is also available on all subdomains like
doc.nette.org
. This can also be achieved with the special value domain
, ie
cookieDomain: domain
.
The default value of cookieSecure
is auto
whitch means that if the website is running on HTTPS,
cookies will be sent with the Secure
flag and will therefore only be available via HTTPS.
HTTP proxy
If the site is running behind an HTTP proxy, enter its IP address in order to correctly detect the IP address of the client Nette\Http\Response::getRemoteAddress() and encrypted connection isSecured().
http:
# IP address, range (ie. 127.0.0.1/8) or array of these values
proxy: 127.0.0.1 # (string|string[]) defaults to none
Including files
Additional configuration files can be inserted in the includes
section:
includes:
- parameters.php
- services.neon
- presenters.neon
The name parameters.php
is not a typo, the configuration can also be written in a PHP file, which returns it as
an array:
<?php
return [
'database' => [
'main' => [
'dsn' => 'sqlite::memory:',
],
],
];
If items with the same keys appear within configuration files, they will be overwritten or merged in the case of arrays. Later included file
has a higher priority than the previous one. The file in which the includes
section is listed has a higher priority
than the files included in it.
Latte
This setting globally affects the behavior of Latte in components and presenters.
latte:
# switches Latte to XHTML mode
xhtml: ... # (bool) defaults to false
# generates templates with declare(strict_types=1)
strictTypes: ... # (bool) defaults to false
# class of $this->template
templateClass: App\MyTemplateClass # defaults to Nette\Bridges\ApplicationLatte\DefaultTemplate
It is also possible to register new tags either by entering the class name or by referring to the service. Method
install()
is called by default, but this can be changed by specifying the name of another method:
latte:
# registration of user Latte tags
macros:
- App\MyLatteMacros::register # static method, classname or callable
- @App\MyLatteMacrosFactory # service with install method
- @App\MyLatteMacrosFactory::register # service with register method
services:
- App\MyLatteMacrosFactory
By default, the mailer Nette\Mail\SendmailMailer
is used to send emails, which is
not further configured. However, we can switch it to Nette\Mail\SmtpMailer
:
mail:
# use SmtpMailer
smtp: true # (bool) defaults to false
host: ... # (string)
port: ... # (int)
username: ... # (string)
password: ... # (string)
timeout: ... # (int)
secure: ... # (ssl|tls|null) defaults to null
clientHost: ... # (string) defaults to $_SERVER['HTTP_HOST']
persistent: ... # (bool) defaults to false
# context for connecting to the SMTP server, see stream_context_create()
context: # (array) defaults to stream_context_get_default()
To increase trustfulness, we can sign emails using DKIM technology:
mail:
dkim:
domain: myweb.com
selector: lovenette
privateKey: %appDir%/cert/dkim.priv
passPhrase: ...
Parameters
You can define parameters that can then be used as part of service definitions. This can help to separate out values that you will want to change more regularly.
parameters:
dsn: 'mysql:host=127.0.0.1;dbname=test'
user: root
password: secret
You can refer to foo
parameter via %foo%
elsewhere in any config file. They can also be used inside
strings like '%wwwDir%/images'
.
Parameters do not need to be just strings, they can also be array values:
parameters:
mailer:
host: smtp.example.com
secure: ssl
user: franta@gmail.com
languages: [cs, en, de]
You can refer to single key as %mailer.user%
.
If you use a string that starts with @
or has %
anywhere in it, you need to escape it by
adding another @
or %
.
If you need to get the value of any parameter in your code, for example in your class, then pass it to this class. For example, in the constructor. There is no global configuration object which can classes query for parameter values. This would be against to the principle of dependency injection.
PHP
You can set PHP directives. An overview of all directives can be found at php.net.
php:
date.timezone: Europe/Prague
Routing
Basic settings:
routing:
# shows routing panel in Tracy Bar?
debugger: ... # (bool) defaults to true
# to serialize router to DI container?
cache: ... # (bool) defaults to false
Router is usually defined in the RouterFactory class, a more limited alternative can be defined in the configuration using
pairs mask: action
:
routing:
routes:
'detail/<id>': Admin:Home:default
'<presenter>/<action>': Front:Home:default
Search
The automatic adding of services to the DI container makes work extremely pleasant. Nette automatically adds presenters to the container, but you can easily add any other classes.
Just specify in which directories (and subdirectories) the classes should be search for:
search:
# you choose the section names yourself
myForms:
in: %appDir%/Forms
model:
in: %appDir%/Model
Usually, however, we don't want to add all the classes and interfaces, so we can filter them:
search:
myForms:
in: %appDir%/Forms
# filtering by file name (string|string[])
files:
- *Factory.php
# filtering by class name (string|string[])
classes:
- *Factory
Or we can select classes that inherit or implement at least one of the following classes:
search:
myForms:
extends:
- App\*Form
implements:
- App\*FormInterface
You can also define negative rules, ie class name masks or ancestors and if they comply, the service will not be added to the DI container:
search:
myForms:
exclude:
classes: ...
extends: ...
implements: ...
Tags can be set for added services:
search:
myForms:
tags: ...
Access Control
You can define a list of users in the configuration to create a simple
authenticator (Nette\Security\SimpleAuthenticator
). Because passwords are readable in the configuration, this
solution is for testing purposes only.
security:
# shows user panel in Tracy Bar?
debugger: ... # (bool) defaults to true
users:
# name: password
johndoe: secret123
# name, password, role and other data available in the identity
janedoe:
password: secret123
roles: [admin]
data: ...
You can also configure how to store information about the logged in user:
security:
authentication:
# after how long of inactivity the user will be logged out
expiration: 30 minutes # (string) default is not set
# where to store information about the logged in user
storage: session # (session|cookie) default is session
If you choose cookie
as your repository, you can also set the following options:
security:
authentication:
# jméno cookie
cookieName: userId # (string) výchozí je userid
# which hosts are allowed to receive the cookie
cookieDomain: 'example.com' # (string|domain)
# restrictions when accessing cross-origin request
cookieSamesite: None # (Strict|Lax|None) defaults to Lax
You can also define roles and resources to create a basis for authorizer
(Nette\Security\Permission
):
security:
roles:
guest:
registered: [guest] # registered inherits from guest
admin: [registered] # and admin inherits from registered
resources:
article:
comment: [article] # resource inherits from article
poll:
Session
Basic sessions settings:
session:
# shows session panel in Tracy Bar?
debugger: ... # (bool) defaults to false
# inactivity time after which the session expires
expiration: 14 days # (string) defaults to '3 hours'
# to start a session automatically after creating a container?
# 'smart' starts a session if it is already created
autoStart: ... # (bool|smart) defaults to 'smart'
# handler, service that implements the SessionHandlerInterface interface
handler: @handlerService
You can also set all PHP session directives (in camelCase format) and also readAndClose. Example:
session:
# 'session.name' written as 'name'
name: MYID
# 'session.save_path' written as 'savePath'
savePath: "%tempDir%/sessions"
Session Cookie
The default values are taken from the HTTP cookie setting, and you can also set the following values:
session:
# which hosts are allowed to receive the cookie
cookieDomain: 'example.com' # (string|domain)
# restrictions when accessing cross-origin request
cookieSamesite: None # (Strict|Lax|None) defaults to Lax
The cookieSamesite
option affects whether the cookie is sent with cross-origin requests, which provides some protection against Cross-Site Request Forgery attecks.
Tracy debugger
You can set the Tracy parameters in the configuration and also add new panels to the Tracy Bar. These settings are applied only after the DI container has been created, so errors that occurred earlier cannot reflect them.
Error logging configuration:
tracy:
# if error has occurred the notification is sent to this email
email: dev@example.com # (string|string[]) defaults to unset
# email sender
fromEmail: robot@example.com # (string) defaults to unset
# to use a mailer defined in the configuration? (since Tracy 2.5)
netteMailer: ... # (bool) defaults to true
# for which error levels is BlueScreen also logged?
logSeverity: [E_WARNING, E_NOTICE] # defaults to []
Configuration for function dump()
:
tracy:
# maximum string length
maxLength: 150 # (int) default according to Tracy
# how deep will list
maxDepth: 10 # (int) default according to Tracy
# hide values of these keys (since Tracy 2.8)
keysToHide: [password, pass] # (string[]) defaults to []
# visual theme (since Tracy 2.8)
dumpTheme: dark # (light|dark) defaults to 'light'
# displays the location where dump() was called?
showLocation: ... # (bool) default according to Tracy
To install the Tracy extension:
tracy:
# appends bars to Tracy Bar
bar:
- Nette\Bridges\DITracy\ContainerPanel
- IncludePanel
- XDebugHelper('myIdeKey')
- MyPanel(@MyService)
# append panels to BlueScreen
blueScreen:
- DoctrinePanel::renderException
Other options:
tracy:
# in Development mode, you will see notice or error warnings as BlueScreen
strictMode: ... # (bool) defaults to true
# displays silent (@) error messages
scream: ... # (bool) defaults to false
# link format to open in the editor
editor: .... # (string) defaults to 'editor://open/?file=%file&line=%line'
# path to template with custom page for error 500
errorTemplate: ... # (string) defaults to unset
# shows Tracy Bar?
showBar: ... # (bool) defaults to true
editorMapping:
# original: new
/var/www/html: /data/web
/home/web: /srv/html
Services and Modifications
The configuration is a place where we add the definitions of our own services in section services
. A detailed
description can be found in chapter Services.
For example, this is the definition of service named database
which is PDO
instance:
services:
database: PDO('mysql:host=127.0.0.1;dbname=test', root, password)
In addition, there are a number of services in the DI container that have added by built-in or your
extensions. The definitions of these services can be changed in the configuration. For example, we can change the class of
service application.application
, which is by default Nette\Application\Application
:
services:
application.application:
factory: MyApplication
alteration: true
The alteration
flag is informative and says we only modify an existing service.
We can also add setup:
services:
application.application:
factory: MyApplication
alteration: true
setup:
- $onStartup = [@resource::init]
You can also remove a service added by an extension from the container:
services:
cache.journal: false