PHP code example of velt / database

1. Go to this page and download the library: Download velt/database library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

velt / database example snippets


use Velt\Database\DB;

$user = DB::table('users')->where('email', $email)->first();
$users = DB::table('users')->select('id', 'name')->orderBy('id')->limit(10)->get();
DB::table('users')->insert(['name' => 'Ada', 'email' => '[email protected]']);
DB::table('users')->where('id', 1)->update(['name' => 'Ada Lovelace']);
DB::table('users')->where('id', 1)->delete();

use Velt\Database\Schema\Blueprint;
use Velt\Database\Schema\Schema;

Schema::create('users', function (Blueprint $table): void {
    $table->id();
    $table->string('name');
    $table->integer('age');
    $table->timestamps();
});

Schema::drop('users');

use Velt\Database\Migrations\Migrator;

$migrator = new Migrator(__DIR__ . '/database/migrations');
$migrator->migrate();
$migrator->rollback();

use Velt\Database\Seeders\Seeder;

final class UserSeeder extends Seeder
{
    public function run(): void
    {
        DB::table('users')->insert(['name' => 'Ada', 'email' => '[email protected]']);
    }
}

use Velt\Database\Factories\Factory;

final class UserFactory extends Factory
{
    public function definition(): array
    {
        return ['name' => 'Ada', 'email' => '[email protected]'];
    }

    protected function table(): string
    {
        return 'users';
    }
}

use Velt\Database\Cache\FileDatabaseCache;

DB::setCache(new FileDatabaseCache(__DIR__ . '/storage/database-cache'));

$users = DB::table('users')->where('active', 1)->remember(60)->get();
DB::cache()->flush();

// SQLite (fichier ou mémoire)
'sqlite' => [
    'driver' => 'sqlite',
    'database' => ':memory:'  // ou '/path/to/db.sqlite'
]

// MySQL
'mysql' => [
    'driver' => 'mysql',
    'host' => 'localhost',
    'port' => 3306,
    'database' => 'velt',
    'charset' => 'utf8mb4'
]

// PostgreSQL
'pgsql' => [
    'driver' => 'pgsql',
    'host' => 'localhost',
    'port' => 5432,
    'database' => 'velt'
]

public function create(array $connection): PDO
// Retourne une instance PDO configurée

private function buildDsn(array $connection): string
// Construit la chaîne de connexion appropriée

private function buildSqliteDsn(array $connection): string
private function buildMysqlDsn(array $connection): string
private function buildPgsqlDsn(array $connection): string
// Builders spécifiques par driver

// Première fois: création et cache
$pdo = $manager->connection('default');  // crée et cache

// Fois suivante: retour du cache
$pdo = $manager->connection('default');  // retour cache, pas de reconnexion

// config/database.php
return [
    'default' => 'sqlite',  // connexion par défaut
    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'database' => ':memory:'
        ],
        // autres connexions...
    ]
];

public function connection(?string $name = null): PDO
// Obtenir une connexion (crée ou retourne du cache)

private function defaultConnectionName(): string
// Résoudre le nom de connexion par défaut depuis config

//  AUTORISÉ - Requête préparée
DB::select('SELECT * FROM users WHERE id = ?', [1]);
DB::select('SELECT * FROM users WHERE email = ?', [$email]);

//  INTERDIT - Interprétation SQL interdite
// (Les placeholders ? sont obligatoires)

// Retourner tous les résultats
public static function select(string $sql, array $bindings = []): array

// Retourner le premier résultat ou null
public static function first(string $sql, array $bindings = []): ?array

// Exécuter INSERT/UPDATE/DELETE, retourner le nombre de lignes affectées
public static function statement(string $sql, array $bindings = []): int

// Transaction: commit si succès, rollback si exception
public static function transaction(callable $callback): mixed

// SELECT
$users = DB::select('SELECT * FROM users WHERE age > ?', [18]);

// FIRST
$user = DB::first('SELECT * FROM users WHERE email = ?', ['[email protected]']);

// INSERT/UPDATE/DELETE
$affected = DB::statement(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    ['John', '[email protected]']
);

// TRANSACTION
DB::transaction(function() {
    DB::statement('INSERT INTO logs (action) VALUES (?)', ['action1']);
    DB::statement('INSERT INTO logs (action) VALUES (?)', ['action2']);
    // Si une exception: rollback automatique
});

// Définir un modèle
class User extends Model
{
    protected string $table = 'users';
}

// Utiliser le modèle
$user = User::find(1);           // SELECT * FROM users WHERE id = 1
$users = User::all();             // SELECT * FROM users
$id = User::create([              // INSERT INTO users (...)
    'name' => 'John',
    'email' => '[email protected]'
]);

// Retrouver par ID (retourne array ou null)
public static function find(int|string $id): ?array

// Récupérer tous les enregistrements
public static function all(): array

// Créer un nouvel enregistrement (retourne l'ID)
public static function create(array $attributes): int

// (Interne) Nom de la table
protected static function tableName(): string

public function register(ContainerInterface $container): void
{
    // Enregistrer comme singleton
    $container->singleton(DatabaseManager::class, function() use ($container) {
        $config = $container->get(ConfigRepositoryInterface::class);
        return new DatabaseManager($config);
    });
}

// Dans le kernel ou bootstrap
$serviceProvider = new DatabaseServiceProvider();
$serviceProvider->register($container);

// Le DatabaseManager n'est créé que lors du premier accès
$manager = $container->get(DatabaseManager::class);

// config/database.php
return [
    // Connexion par défaut utilisée par DB::
    'default' => env('DB_CONNECTION', 'sqlite'),
    
    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', ':memory:'),
        ],
        
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 3306),
            'database' => env('DB_DATABASE', 'velt'),
            'charset' => 'utf8mb4',
        ],
        
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 5432),
            'database' => env('DB_DATABASE', 'velt'),
        ],
    ],
];

// Dans le kernel
use Velt\Database\DatabaseServiceProvider;

class Kernel
{
    protected array $serviceProviders = [
        // ... autres providers
        DatabaseServiceProvider::class,
    ];
}

use Velt\Database\DB;

// Requêtes SELECT
$users = DB::select('SELECT * FROM users WHERE active = ?', [1]);
$user = DB::first('SELECT * FROM users WHERE id = ?', [1]);

// Modification de données
$affected = DB::statement(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    ['Alice', '[email protected]']
);

// Transactions
DB::transaction(function() {
    DB::statement('UPDATE users SET balance = balance - ? WHERE id = ?', [100, 1]);
    DB::statement('UPDATE users SET balance = balance + ? WHERE id = ?', [100, 2]);
    // Les deux exécutées, ou rien si erreur
});

use Velt\Database\Model;

class User extends Model
{
    protected string $table = 'users';
}

// Créer
$id = User::create([
    'name' => 'Bob',
    'email' => '[email protected]'
]);

// Lire
$user = User::find(1);
$users = User::all();

//  UPDATE et DELETE ne sont pas implémentés en MVP
// Utiliser DB::statement() pour ces opérations

// Paramètres bindés de manière sécurisée
DB::select('SELECT * FROM users WHERE email = ?', [$userInput]);
DB::select('SELECT * FROM users WHERE email = ? AND role = ?', [$email, $role]);

// JAMAIS FAIRE CELA - INJECTION SQL!
$sql = "SELECT * FROM users WHERE email = '$userInput'";

try {
    $pdo = $factory->create(['driver' => 'invalid']);
} catch (UnknownDatabaseDriverException $e) {
    // Message d'erreur explicite
}

// ConnectionFactory crée les instances PDO
$factory = new ConnectionFactory();
$pdo = $factory->create($config);

// Enregistrer les services au démarrage
$provider = new DatabaseServiceProvider();
$provider->register($container);

// Interface simple et statique
DB::select(...);
DB::transaction(...);

// DatabaseManager créé une seule fois
$container->singleton(DatabaseManager::class, ...);

// Les dépendances sont injectées, pas créées localement
public function __construct(
    private ConfigRepositoryInterface $config,
) {}

// Abstraction de la source de config
interface ConfigRepositoryInterface {
    public function get(string $key, mixed $default = null): mixed;
}

// Base
DatabaseConfigurationException extends RuntimeException

// Spécifiques
UnknownDatabaseDriverException extends DatabaseConfigurationException

tests/
├── Fakes/
│   ├── ArrayConfigRepository.php    # Fake ConfigRepository
│   └── ArrayContainer.php           # Fake ContainerInterface
├── ConnectionFactoryTest.php        # 5 tests
├── DatabaseManagerTest.php          # 4 tests
├── DBTest.php                       # 5 tests
├── ModelTest.php                    # 3 tests
└── DatabaseServiceProviderTest.php  # 2 tests

src/
├── ConnectionFactory.php                  # Crée PDO
├── DatabaseManager.php                    # Pool de connexions
├── DB.php                                 # Facade statique
├── Model.php                              # Classe de base
├── DatabaseServiceProvider.php            # Enregistrement DI
└── Contracts/
    ├── ConfigRepositoryInterface.php      # Configuration
    └── ContainerInterface.php             # DI Container

tests/
├── Fakes/
│   ├── ArrayConfigRepository.php          # Test config
│   └── ArrayContainer.php                 # Test DI
├── ConnectionFactoryTest.php
├── DatabaseManagerTest.php
├── DBTest.php
├── ModelTest.php
└── DatabaseServiceProviderTest.php