twoh / database-driver
Includes a basic Driver to interact with different database systems.
Requires
- php: ^8.3
- ext-mongodb: *
- mongodb/mongodb: ^1.19
- twoh/logger: ^1
- twoh/validator: ^1
- vlucas/phpdotenv: ^5.6
Requires (Dev)
- ext-xdebug: *
- phpunit/phpunit: ^11
- roave/security-advisories: dev-latest
README
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 Name | Final Container Name | Purpose |
---|---|---|
php | database_driver_php83_container | PHP 8.3 Environment |
mongodb | database_driver_mongodb_container | MongoDB 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.