Drivers

The Doctrine Driver

Introduction

The Doctrine driver provides a powerful and flexible way to interact with various databases using the Doctrine ORM (or DBAL).

It's based on the latest version 4.x of Doctrine and supports a wide range of database systems, including MySQL, PostgreSQL, SQLite, and more.

You can use it to configure multiple DBAL and Entity Manager connections in your API.

Installation

Install the driver via composer by running:

composer require kipchak/driver-doctrine

Initialise the Driver

Add the following line to your drivers/drivers.php file:

\Mamluk\Kipchak\Driver\Doctrine\Doctrine::iniitalise($container);

Configuration

The configuration in kipchak.doctrine.php can be used to configure muliple DBAL and ORM connections:

return [
    'dbal' => [
        'enabled' => false,
        'connections' => [
            'primary' => [
                'dbname' => 'mydb',
                'user' => env('DB_USER', 'api'),
                'password' => env('DB_PASSWORD', 'api'),
                'host' => env('DB_HOST', 'mysql'),
                'driver' => 'pdo_mysql',
            ]
        ]
    ],
    'orm' => [
        'enabled' => false,
        'entity_managers' => [
            'primary' => [
                'dev_mode' => (bool) env('DEBUG', true),
                'metadata_dirs' => [
                    realpath(__DIR__ . '/../api/Entities/Doctrine/Primary')
                ],
                'connection' => 'primary',
            ],
        ]
    ]
];

Please see the configuration file in the starter project at https://1x.ax/mamluk/kipchak/starter/~files/master/config/kipchak.doctrine.php for full configuration details.

Usage

DBAL Usage

use Kipchak\Driver\Doctrine\Doctrine;

$dbal = Doctrine::get('dbal.primary'); //See config file below for DBAL definition

// Query builder
$queryBuilder = $dbal->createQueryBuilder();
$users = $queryBuilder
    ->select('*')
    ->from('users')
    ->where('status = ?')
    ->setParameter(0, 'active')
    ->executeQuery()
    ->fetchAllAssociative();

// Direct queries
$stmt = $dbal->executeQuery('SELECT * FROM users WHERE id = ?', [123]);
$user = $stmt->fetchAssociative();

ORM Usage

use Kipchak\Driver\Doctrine\Doctrine;

$em = Doctrine::get('entitymanager.primary'); // See config file below for ORM EM definition

// Find entity
$user = $em->find(User::class, 123);

// Create entity
$newUser = new User();
$newUser->setName('John Doe');
$newUser->setEmail('john@example.com');
$em->persist($newUser);
$em->flush();

// Query
$users = $em->getRepository(User::class)
    ->findBy(['status' => 'active']);

Learn more about Doctrine DBAL and ORM at https://www.doctrine-project.org/projects.html.

Git Repository

The source code for this driver is available on 1x.ax at https://1x.ax/mamluk/kipchak/drivers/doctrine.

Previous
Filecache