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/ */
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';
}
}
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
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);
// 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'";