Connection handling with the connection pool
Because database connections are required in very different parts of an application but it does not make sense to handle connection instances throughout the application a connection pool can be used that holds all database connections and returns the required connection when it is needed. For this reason Stubbles contains a stubDatabaseConnectionPool that is capable of managing all database connections. This chapter will show how to use the connection pool. For informations how to configure the connection pool see Database configuration. For the following examples we assume that we have a fully configured connection pool. It should be noted that the stubDatabaseConnectionPool is a completely static class.
Getting a connection
To retrieve a connection from the connection pool you need to know its id. If you only have one connection, this id will be mostly likely __default. The connection pool will return an instance of stubDatabaseConnection:
<?php $connection = stubDatabaseConnectionPool::getConnection(); ?>
If you need to retrieve a connection with another id use this:
<?php $connection = stubDatabaseConnectionPool::getConnection('anotherConnectionId'); ?>
In case no connection with the given id is configured, a stubDatabaseException will be thrown. To prevent such exceptions you could check if the connection pool knows a connection with the given id:
<?php if (stubDatabaseConnectionPool::hasConnectionData('connectionIdToCheck') == true) { echo 'Connection with id connectionIdToCheck is known!'; } else { echo 'Unknown connection!'; } ?>
You can get a list of all known ids via stubDatabaseConnectionPool::getConnectionDataIds().
The connection pool will check if a connection instance for the given id already exists. If it does, this connection instance will be returned. If it does not, the connection pool will try to create it from the connection configuration. If the configured connection class to use does not exist, a stubClassNotFoundException will be thrown, if the configured connection class is not an instance of stubDatabaseConnection a stubDatabaseException will be thrown.
The returned connection instance does not necessarily hold a connection to the database yet. It should be assumed that it will open this connection on the first request, thus it is possible to get an exception that says something like Could not connect to database server even after the connection instance was retrieved from the connection pool.
Closing a connection
To close a connection the disconnect() method can be called on the connection object. However we recommend using stubDatabaseConnectionPool::closeConnection('idOfConnectionToClose'); instead because this will remove the connection instance as well. Using this method will keep the connection data in the pool which allows to re-establish the connection later on.
