This document assumes you’ve installed hiraeth/bootstrap
or hiraeth/dbal
. If you haven’t your mileage may vary. See the installation docs for more information.
Hiraeth’s database access and datbase abstraction layer is powered by Doctrine’s DBAL library.
Connections are the starting point for database functionality, they enable you to execute queries (including prepared statements) as well as gain access to additional utilities for things like schema inflection, building queries, etc.
Each connection is defined by a JIN configuration file containing a [connection]
section. For example config/connections/default.jin
contains the settings for the connection named default
. By default, this configuration will read from environment variables, so unless you have need to add an additional configuration or want to source these values elsewhere, you can simply define these settings in your .env
file:
[DATABASES]
[&.DEFAULT]
TYPE = pdo_pgsql
NAME = database
USER = user
; PASS = myP@ssW0rd
; HOST = not.localhost.com
; PORT = 31337
Hiraeth’s DBAL integration supports mulitple connections out of the box, so the preferred way to obtain your connection is to inject the Hiraeth\Dbal\ConnectionRegistry
:
use Hiraeth\Dbal\ConnectionRegistry;
class MyService
{
public function __construct(ConnectionRegistry $registry)
{
$this->connection = $registry->getConnection('default');
}
}
Once you’ve obtained a connection, you should be able to use it in accordance with Doctrine’s documentation. In the above example, the name is optional, but if not provided will always attempt to return the connection named default
.
Adding a Connection
Connections can be added by creating a new connection configuration in the config/dbal
directory. The basename of the configuration (minus the .jin
extension) will be the name of the connection.
The connection file itself is relatively straightforward. Let’s copy the default.jin
called blog.jin
and modify a few things. We’ll change our environment variable names to match our blog settings, and uncomment the password as we’ll need a password to access this database.
[connection]
driver = env(DATABASES_BLOG_TYPE)
dbname = env(DATABASES_BLOG_NAME)
user = env(DATABASES_BLOG_USER)
password = env(DATABASES_BLOG_PASS)
Now we can add our .env
settings accordingly:
[DATABASES]
[&.BLOG]
TYPE = pdo_mysql
NAME = blog
USER = bloguser
PASS = myS3cr3tP455werd
Finally, we can get our blog connection thusly:
use Hiraeth\Dbal\ConnectionRegistry;
class MyBlogService
{
public function __construct(ConnectionRegistry $registry)
{
$this->connection = $registry->getConnection('blog');
}
}
To enable the ORM, you’ll need to add hiraeth/doctrine
and configure the entity manager.