Configuration and connections
The Settings class describes where queries live and how a connection should be made.
Constructor arguments
The constructor accepts:
- query base directory
- driver
- schema, database name, or SQLite file path
- host
- port
- username
- password
- connection name
- collation
- charset
- initial SQL to run after connecting
In many projects we only need the first three arguments for SQLite, or the first seven for MySQL or PostgreSQL.
Driver constants
The built-in driver constants are:
Settings::DRIVER_SQLITESettings::DRIVER_MYSQLSettings::DRIVER_POSTGRESSettings::DRIVER_SQLSERVER
There is also Settings::SCHEMA_IN_MEMORY for an in-memory SQLite database.
Common examples
SQLite:
$settings = new Settings(
"query",
Settings::DRIVER_SQLITE,
"app.sqlite"
);
SQLite in memory:
$settings = new Settings(
"query",
Settings::DRIVER_SQLITE,
Settings::SCHEMA_IN_MEMORY
);
MySQL:
$settings = new Settings(
"query",
Settings::DRIVER_MYSQL,
"app_db",
"localhost",
3306,
"app_user",
"app_pass"
);
Immutable helpers
Settings uses immutable helpers, so changing one value returns a new object.
$reportingSettings = $settings
->withConnectionName("reporting")
->withHost("db.internal")
->withPort(3307);
Available helpers include:
withBaseDirectory()withDriver()withSchema()withHost()withPort()withUsername()withPassword()withConnectionName()withoutSchema()withCharset()withCollation()withInitQuery()
Charset, collation, and init SQL
The defaults are utf8mb4 and utf8mb4_general_ci.
If we need to change those values, we can do so explicitly:
$settings = $settings
->withCharset("utf8mb4")
->withCollation("utf8mb4_unicode_ci");
If the connection needs one or more statements to run as soon as it opens, we can use withInitQuery():
$settings = $settings->withInitQuery(implode(";", [
"pragma foreign_keys = on",
"pragma busy_timeout = 5000",
]));
Extra PDO configuration
Settings::setConfig() allows us to merge additional connection configuration into the defaults:
$settings->setConfig([
"options" => [
PDO::ATTR_PERSISTENT => false,
],
]);
This is mainly useful when we need to adjust the underlying PDO options.
PHP query namespaces
If we use PHP query collection classes, the default namespace is \App\Query.
We can change that at the Database or QueryCollection level:
$db->setAppNameSpace("MyProject\\Query");
That is covered in more detail on Query collections.
[!NOTE] In WebEngine we usually express these settings in
config.iniinstead of constructingSettingsmanually. The framework then creates the database service for us.
Next, move on to Query collections to see how query names map to files and PHP classes.