Db::__construct
Usage
Db::__construct([ array $params = [] ], [ array $readonly_params = [] ], [ ?redis $redis = null ], [ ?DebuggerInterface $debugger = null ], [ ?callable $onconnect_fail = null ], [ string $charset = 'utf8mb4' ], [ string $tz_offset = '+0:00' ])Description
Instantiate a new database connection object. With Apex you will never need to execute this method as the database connection is available via the `Apex\Svc\Db` service. The only time you may need this method is if you're connecting to a secondary / remote database.Parameters
Parameter | Required | Type | Description |
---|---|---|---|
$params | No | array | Associative array of connection parameters for the main connection. Supported keys are: dbname, user, password, host, port |
$readonly_params | No | array | Optional associative array of connection parameters for a read-only connection. Supported keys are: dbname, user, password, host, port |
$redis | No | ?redis | Optional redis instance if storing the database connection within redis, which is default for Apex. For full information, see the redis Connection Manager page of the documentation. |
$debugger | No | ?DebuggerInterface | Optional instance of the Apex Debugger. |
$onconnect_fail | No | ?callable | An optional callback that will be executed upon failure to connect to the database. |
$charset | No | string | Optional charset to use as default. Defaults to utf8mb4 |
$tz_offset | No | string | Optional timezone offset to use for the connection. Defaults to UTC. |
Return Value
Does not return anything, nor does this connect to the database. Instead, it saves the connection information and will connect as needed when the first SQL query is executed.Examples
Inject into Apex
namespace App\Demo;
use Apex\Svc\Db;
class MyClass
{
#[Inject(Db::class)]
private Db $db;
/**
* Do something
*/
public function doSomething():void
{
$rows = $this->db->query("SELECT * FROM some_table WHERE is_active = %b AND name LIKE %ls", true, 'search_term');
foreach ($rows as $row) {
print_r($row);
}
}
}
Instantiate Secondary Connection
use Apex\Db\Drivers\mySQL\mySQL;
$params = [
'dbname' => 'mydb',
'user' => 'myuser',
'password' => 'secret_password'
]);
// Connect
$db = new mySQL($params);
// Get tables
$tables = $db->getTableNames();
print_r9$tables);