twoh/database-driver

Includes a basic Driver to interact with different database systems.

1.0.5 2025-01-23 14:53 UTC

This package is auto-updated.

Last update: 2025-02-23 15:04:37 UTC


README

TWOH Logo

Build Status Latest Stable Version License

About Database-Driver

This project includes a basic Driver to interact with different database systems.

Like:

  • MongoDB

Requirements

  • PHP 8.3 or higher
  • Composer

Installation

composer req twoh/database-driver

Usage

Starting Docker

To start the Docker containers, navigate to the project directory and use the following command:

docker-compose up -d --build

Docker Containers

Docker Container NameFinal Container NamePurpose
phpdatabase_driver_php83_containerPHP 8.3 Environment
mongodbdatabase_driver_mongodb_containerMongoDB Environment

Setup Connection

use TWOH\DatabaseDriver\Exceptions\MigrationException;
use TWOH\DatabaseDriver\Models\Configuration;
use TWOH\DatabaseDriver\Models\Migration;
use TWOH\DatabaseDriver\Services\DatabaseDriverService;
use Dotenv\Dotenv;

require __DIR__ . '/../vendor/autoload.php';

// load .env file
$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

$query = (new DatabaseDriverService(
    new Configuration(
        'MongoDb',
        $_ENV['DB_HOST'],
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        (int)$_ENV['DB_PORT'],
        $_ENV['DB_DATABASE']
    )
))->__invoke();

Migrate Colletions and Table fields

First of all you need to create a migration file in the Migrations folder. The migration file should be structured as follows:

use TWOH\DatabaseDriver\Models\Migration;

return [
     new Migration(
         'test',
         [
             'name' => 'string',
             'age' => 'int',
             'email' => 'string'
         ]
     ),
     new Migration(
         'test2'
     )
]

Then you need to start the migration service and load the migration files by correct path. All migration files inside the folder path will be loaded automatically.

$migrationPath = __DIR__ . '/../../Migrations/';
$migrationService = new MigrationService(
    $query->getConfiguration(),
    $query
);
$migrationService->loadMigrations(
    $migrationPath
);

Use Queries

You can find a full list of queries here or in the documentation/queries/queries.md folder.

$query->insertOne(
    'test',
    [
        'name' => 'John Doe',
        'age' => 42,
        'email' => 'j.doe@example.org'
    ]
);

Running Tests

To verify that the tests are passing, run the following command:

vendor/bin/phpunit

Logging

This project uses its own LoggerTrait class. You can integrate it into your classes to log messages as follows:

use LoggerTrait;

$this->info('Your message here');
$this->warning('Your message here');
$this->error('Your message here');

The log files will be stored in the logs folder.