DbConfig
- Type
- Class
- Namespace
- craft\config
- Inherits
- craft\config\DbConfig » craft\config\BaseConfig » craft\base\Model » yii\base\Model » yii\base\Component » yii\base\BaseObject
- Implements
- ArrayAccess, IteratorAggregate, craft\base\ModelInterface, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
- Uses traits
- craft\base\ClonefixTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
- Since
- 3.0.0
DB config class
Public Properties
Property | Description |
---|---|
activeValidators | yii\validators\Validator – The validators applicable to the current scenario. |
attributes | array – An array of key-value pairs of PDO attributes to pass into the PDO constructor. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
charset | string – The charset to use when creating tables. |
collation | string, null – The collation to use when creating tables. |
database | string, null – The name of the database to select. |
driver | string, null – The database driver to use. |
dsn | string, null – The Data Source Name (“DSN”) that tells Craft how to connect to the database. |
errors | array – Errors for all attributes or the specified attribute. |
firstErrors | array – The first errors. |
iterator | ArrayIterator – An iterator for traversing the items in the list. |
password | string – The database password to connect with. |
port | integer, null – The database server port. |
scenario | string – The scenario that this model is in. |
schema | string, null – The schema that Postgres is configured to use by default (PostgreSQL only). |
server | string, null – The database server name or IP address. |
setSchemaOnConnect | boolean – Whether the schema() should be explicitly used for database queries (PostgreSQL only). |
tablePrefix | string, null – If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. |
unixSocket | string, null – MySQL only. |
url | string, null – The database connection URL, if one was provided by your hosting environment. |
useUnbufferedConnections | boolean – Whether batched queries should be executed on a separate, unbuffered database connection. |
user | string – The database username to connect with. |
validators | ArrayObject, yii\validators\Validator – All the validators declared in the model. |
attributes
- Type
- array
- Default value
[]
An array of key-value pairs of PDO attributes to pass into the PDO constructor.
For example, when using the MySQL PDO driver, if you wanted to enable a SSL database connection (assuming SSL is enabled in MySQL and 'user'
can connect via SSL, you’d set these:
->attributes([
PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem',
])
charset
- Type
- string
- Default value
'utf8'
The charset to use when creating tables.
TIP
You can change the character set and collation across all existing database tables using this terminal command:
php craft db/convert-charset
::: code
->charset('utf8mb4')
CRAFT_DB_CHARSET=utf8mb4
:::
collation
The collation to use when creating tables.
This is only used by MySQL. If null, the charset’s default collation will be used.
Charset | Default collation |
---|---|
utf8 | utf8_general_ci |
utf8mb4 | utf8mb4_0900_ai_ci |
TIP
You can change the character set and collation across all existing database tables using this terminal command:
php craft db/convert-charset
::: code
->collation('utf8mb4_0900_ai_ci')
CRAFT_DB_COLLATION=utf8mb4_0900_ai_ci
:::
database
The name of the database to select.
::: code
->database('mydatabase')
CRAFT_DB_DATABASE=mydatabase
:::
driver
The database driver to use. Either mysql
for MySQL or pgsql
for PostgreSQL.
::: code
->driver('mysql')
CRAFT_DB_DRIVER=mysql
:::
dsn
The Data Source Name (“DSN”) that tells Craft how to connect to the database.
DSNs should begin with a driver prefix (mysql:
or pgsql:
), followed by driver-specific parameters. For example, mysql:host=127.0.0.1;port=3306;dbname=acme_corp
.
- MySQL parameters: https://php.net/manual/en/ref.pdo-mysql.connection.php
- PostgreSQL parameters: https://php.net/manual/en/ref.pdo-pgsql.connection.php
::: code
->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp')
CRAFT_DB_DSN=mysql:host=127.0.0.1;port=3306;dbname=acme_corp
:::
password
- Type
- string
- Default value
''
The database password to connect with.
::: code
->password('super-secret')
CRAFT_DB_PASSWORD=super-secret
:::
port
The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL.
::: code
->port(3306)
CRAFT_DB_PORT=3306
:::
schema
The schema that Postgres is configured to use by default (PostgreSQL only).
TIP
To force Craft to use the specified schema regardless of PostgreSQL’s search_path
setting, you must enable the setSchemaOnConnect() setting.
::: code
->schema('myschema,public')
CRAFT_DB_SCHEMA=myschema,public
:::
See also https://www.postgresql.org/docs/8.2/static/ddl-schemas.html
server
The database server name or IP address. Usually localhost
or 127.0.0.1
.
::: code
->server('localhost')
CRAFT_DB_SERVER=localhost
:::
setSchemaOnConnect
- Type
- boolean
- Default value
false
- Since
- 3.7.27
Whether the schema() should be explicitly used for database queries (PostgreSQL only).
WARNING
This will cause an extra SET search_path
SQL query to be executed per database connection. Ideally, PostgreSQL’s search_path
setting should be configured to prioritize the desired schema.
::: code
->setSchemaOnConnect(true)
CRAFT_DB_SET_SCHEMA_ON_CONNECT=true
:::
tablePrefix
If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase.
::: code
->tablePrefix('craft_')
CRAFT_DB_TABLE_PREFIX=craft_
:::
unixSocket
MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server
and port
settings are ignored.
::: code
->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock')
CRAFT_DB_UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
:::
url
The database connection URL, if one was provided by your hosting environment.
If this is set, the values for driver(), user(), database(), server(), port(), and database() will be extracted from it.
::: code
->url('jdbc:mysql://database.foo:3306/mydb')
CRAFT_DB_URL=jdbc:mysql://database.foo:3306/mydb
:::
useUnbufferedConnections
- Type
- boolean
- Default value
false
- Since
- 3.7.0
Whether batched queries should be executed on a separate, unbuffered database connection.
This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent PHP from running out of memory when querying too much data at once. (See https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#batch-query-mysql for an explanation of MySQL’s batch query limitations.)
For more on Craft batch queries, see https://craftcms.com/knowledge-base/query-batching-batch-each.
::: code
->useUnbufferedConnections(true)
CRAFT_DB_USE_UNBUFFERED_CONNECTIONS=true
:::
user
- Type
- string
- Default value
'root'
The database username to connect with.
::: code
->user('db')
CRAFT_DB_USER=db
:::
Protected Properties
Property | Description |
---|---|
filename | string, null – The config filename |
renamedSettings | array – Settings that have been renamed |
filename
The config filename
Public Methods
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
activeAttributes() | Returns the attribute names that are subject to validation in the current scenario. |
addError() | Adds a new error to the specified attribute. |
addErrors() | Adds a list of errors. |
addModelErrors() | Adds errors from another model, with a given attribute name prefix. |
afterValidate() | This method is invoked after validation ends. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
attributeHints() | Returns the attribute hints. |
attributeLabels() | Returns the attribute labels. |
attributes() | Returns the list of attribute names. |
beforeValidate() | This method is invoked before validation starts. |
behaviors() | Returns a list of behaviors that this component should behave as. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSetProperty() | Returns a value indicating whether a property can be set. |
charset() | The charset to use when creating tables. |
className() | Returns the fully qualified name of this class. |
clearErrors() | Removes errors for all attributes or a single attribute. |
collation() | The collation to use when creating tables. |
create() | Factory method for creating new config objects. |
createValidators() | Creates validator objects based on the validation rules specified in rules(). |
database() | The name of the database to select. |
datetimeAttributes() | Returns the names of any attributes that should hold DateTime values. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
driver() | The database driver to use. Either mysql for MySQL or pgsql for PostgreSQL. |
dsn() | The Data Source Name (“DSN”) that tells Craft how to connect to the database. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
extraFields() | Returns the list of fields that can be expanded further and returned by toArray(). |
fields() | Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. |
formName() | Returns the form name that this model class should use. |
generateAttributeLabel() | Generates a user friendly attribute label based on the give attribute name. |
getActiveValidators() | Returns the validators applicable to the current scenario. |
getAttributeHint() | Returns the text hint for the specified attribute. |
getAttributeLabel() | Returns the text label for the specified attribute. |
getAttributes() | Returns attribute values. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getErrorSummary() | Returns the errors for all attributes as a one-dimensional array. |
getErrors() | Returns the errors for all attributes or a single attribute. |
getFirstError() | Returns the first error of the specified attribute. |
getFirstErrors() | Returns the first error of every attribute in the model. |
getIterator() | Returns an iterator for traversing the attributes in the model. |
getScenario() | Returns the scenario that this model is used in. |
getValidators() | Returns all the validators declared in rules(). |
hasErrors() | Returns a value indicating whether there is any validation error. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
instance() | Returns static class instance, which can be used to obtain meta information. |
isAttributeActive() | Returns a value indicating whether the attribute is active in the current scenario. |
isAttributeRequired() | Returns a value indicating whether the attribute is required. |
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. |
load() | Populates the model with input data. |
loadMultiple() | Populates a set of models with the data from end user. |
off() | Detaches an existing event handler from this component. |
offsetExists() | Returns whether there is an element at the specified offset. |
offsetGet() | Returns the element at the specified offset. |
offsetSet() | Sets the element at the specified offset. |
offsetUnset() | Sets the element value at the specified offset to null. |
on() | Attaches an event handler to an event. |
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. |
password() | The database password to connect with. |
pdoAttributes() | An array of key-value pairs of PDO attributes to pass into the PDO constructor. |
port() | The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL. |
rules() | Returns the validation rules for attributes. |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. |
scenarios() | Returns a list of scenarios and the corresponding active attributes. |
schema() | The schema that Postgres is configured to use by default (PostgreSQL only). |
server() | The database server name or IP address. Usually localhost or 127.0.0.1 . |
setAttributes() | Sets the attribute values in a massive way. |
setScenario() | Sets the scenario for the model. |
setSchemaOnConnect() | Whether the schema() should be explicitly used for database queries (PostgreSQL only). |
tablePrefix() | If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase. |
toArray() | Converts the model into an array. |
trigger() | Triggers an event. |
unixSocket() | MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server and port settings are ignored. |
url() | The database connection URL, if one was provided by your hosting environment. |
useUnbufferedConnections() | Whether batched queries should be executed on a separate, unbuffered database connection. |
user() | The database username to connect with. |
validate() | Performs the data validation. |
validateMultiple() | Validates multiple models. |
charset()
- Since
- 4.2.0
The charset to use when creating tables.
TIP
You can change the character set and collation across all existing database tables using this terminal command:
php craft db/convert-charset
->charset('utf8mb4')
Arguments
$value
(string)
Returns
self
collation()
- Since
- 4.2.0
The collation to use when creating tables.
This is only used by MySQL. If null, the charset’s default collation will be used.
Charset | Default collation |
---|---|
utf8 | utf8_general_ci |
utf8mb4 | utf8mb4_0900_ai_ci |
TIP
You can change the character set and collation across all existing database tables using this terminal command:
php craft db/convert-charset
->collation('utf8mb4_0900_ai_ci')
Arguments
Returns
self
database()
- Since
- 4.2.0
The name of the database to select.
->database('mydatabase')
Arguments
Returns
self
Throws
driver()
- Since
- 4.2.0
The database driver to use. Either mysql
for MySQL or pgsql
for PostgreSQL.
->driver('mysql')
Arguments
Returns
self
Throws
dsn()
- Since
- 4.2.0
The Data Source Name (“DSN”) that tells Craft how to connect to the database.
DSNs should begin with a driver prefix (mysql:
or pgsql:
), followed by driver-specific parameters. For example, mysql:host=127.0.0.1;port=3306;dbname=acme_corp
.
- MySQL parameters: https://php.net/manual/en/ref.pdo-mysql.connection.php
- PostgreSQL parameters: https://php.net/manual/en/ref.pdo-pgsql.connection.php
->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp')
Arguments
Returns
self
init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Throws
password()
- Since
- 4.2.0
The database password to connect with.
->password('super-secret')
Arguments
$value
(string)
Returns
self
pdoAttributes()
- Since
- 4.2.0
An array of key-value pairs of PDO attributes to pass into the PDO constructor.
For example, when using the MySQL PDO driver, if you wanted to enable a SSL database connection (assuming SSL is enabled in MySQL and 'user'
can connect via SSL, you’d set these:
->pdoAttributes([
PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem',
PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem',
])
Arguments
$value
(array)
Returns
self
port()
- Since
- 4.2.0
The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL.
->port(3306)
Arguments
Returns
self
Throws
schema()
- Since
- 4.2.0
The schema that Postgres is configured to use by default (PostgreSQL only).
TIP
To force Craft to use the specified schema regardless of PostgreSQL’s search_path
setting, you must enable the setSchemaOnConnect() setting.
->schema('myschema,public')
See also https://www.postgresql.org/docs/8.2/static/ddl-schemas.htmlView source
Arguments
Returns
self
server()
- Since
- 4.2.0
The database server name or IP address. Usually localhost
or 127.0.0.1
.
->server('localhost')
Arguments
Returns
self
Throws
setSchemaOnConnect()
- Since
- 4.2.0
Whether the schema() should be explicitly used for database queries (PostgreSQL only).
WARNING
This will cause an extra SET search_path
SQL query to be executed per database connection. Ideally, PostgreSQL’s search_path
setting should be configured to prioritize the desired schema.
->setSchemaOnConnect()
Arguments
$value
(boolean)
Returns
self
tablePrefix()
- Since
- 4.2.0
If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase.
->tablePrefix('craft_')
Arguments
Returns
self
Throws
unixSocket()
- Since
- 4.2.0
MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server
and port
settings are ignored.
->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock')
Arguments
Returns
self
Throws
url()
- Since
- 4.2.0
The database connection URL, if one was provided by your hosting environment.
If this is set, the values for driver(), user(), database(), server(), port(), and database() will be extracted from it.
->url('jdbc:mysql://database.foo:3306/mydb')
Arguments
Returns
self
useUnbufferedConnections()
- Since
- 4.2.0
Whether batched queries should be executed on a separate, unbuffered database connection.
This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent PHP from running out of memory when querying too much data at once. (See https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#batch-query-mysql for an explanation of MySQL’s batch query limitations.)
For more on Craft batch queries, see https://craftcms.com/knowledge-base/query-batching-batch-each.
->useUnbufferedConnections()
Arguments
$value
(boolean)
Returns
self
user()
- Since
- 4.2.0
The database username to connect with.
->user('db')
Arguments
$value
(string)
Returns
self
Protected Methods
Method | Description |
---|---|
defineBehaviors() | Returns the behaviors to attach to this class. |
defineRules() | Returns the validation rules for attributes. |
extractFieldsFor() | Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". |
extractRootFields() | Extracts the root field names from nested fields. |
resolveFields() | Determines which fields can be returned by toArray(). |
Constants
Constant | Description |
---|---|
DRIVER_MYSQL | |
DRIVER_PGSQL | |
SCENARIO_DEFAULT | The name of the default scenario. |