Skip to content

connecting

Alexey Borzov edited this page Jul 18, 2020 · 2 revisions

Connecting to a DB

Connection to a PostgreSQL database is represented by an instance of sad_spirit\pg_wrapper\Connection. Its constructor accepts a connection string suitable for pg_connect():

use sad_spirit\pg_wrapper\Connection;

$connection = new Connection('host=localhost port=5432 dbname=postgres');

Note that connecting is lazy by default, so instantiating the class will not immediately establish a connection to the database: it will only be established once it is needed (e.g. $connection->execute() is called).

You can request an immediate connection if you pass false as a second argument to the constructor:

use sad_spirit\pg_wrapper\Connection;

$connection = new Connection('host=localhost port=5432 dbname=postgres', false);
var_dump($connection->isConnected());

will output

bool(true)

The connection will be automatically closed once $connection instance is destroyed.

You can also explicitly call connect() and disconnect() methods of Connection instance if needed.

Note: connection will only be established automatically the first time it is needed. Once disconnect() was performed, it will require an explicit connect() to re-establish the connection.