-
-
Notifications
You must be signed in to change notification settings - Fork 3
Configuration and connections
The Settings class describes where queries live and how to connect to the database.
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.
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",
);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.
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");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.ini rather than building Settings manually. 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.
PHP.GT/Database is a separately maintained component that powers database features in PHP.GT/WebEngine.