Configuration and connections
The Settings class describes where queries live and how to connect to the database.
The constructor at a glance
The constructor arguments are:
- base query directory
- driver
- schema or SQLite file path
- host
- port
- username
- password
- connection name
- collation
- charset
- initial SQL to run after connecting
In practice, most projects only need the first three for SQLite, or the first seven for a server database.
Common driver examples
SQLite:
$settings = new Settings(
"query",
Settings::DRIVER_SQLITE,
"app.sqlite"
);
MySQL:
$settings = new Settings(
"query",
Settings::DRIVER_MYSQL,
"my_website",
"localhost",
3306,
"app_user",
"app_pass",
);
Immutable configuration helpers
Settings uses an immutable style. If we change one value, we get back a new object.
$reportingSettings = $settings
->withConnectionName("reporting")
->withHost("db.internal")
->withPort(3307);
This keeps connection changes explicit and third parties cannot modify them.
Multiple connections
If we add more than one Settings object to Database, each connection can have its own name.
use Gt\Database\Database;
$db = new Database($mainSettings, $reportingSettings);
$rows = $db->queryCollection("event", "reporting")
->fetchAll("listRecent");
For raw SQL, the connection name is the third argument:
$db->executeSql("select 1", [], "reporting");
PHP query namespace
If we use PHP query classes instead of SQL files, the default namespace is \App\Query.
$db->setAppNameSpace("MyWebsite\\Query");
[!NOTE] In WebEngine, most projects express these settings in
config.inirather than buildingSettingsmanually. The framework then constructs the database service for you. The WebEngine guide is at https://www.php.gt/docs/webengine/database.
Next, move on to Query collections to see how query names map cleanly to files and classes.