Db API

Module: Db

Namespace root: DafDb

DbContext

DafDb\Context\DbContext | DafPhpFramwork/DafDb/Context/DbContext.php

Summary: base app context that initializes DbSet properties and delegates commit to provider context.

  • __construct(Context $context)
  • ModelSnapshot(SnapshotBuilder $builder): SnapshotBuilder|null
  • getModelSnapshot(): array
  • SaveChanges(): void

Context (Provider Base)

DafDb\Context\Context | DafPhpFramwork/DafDb/Context/Context.php

  • Table(string $dbSetClassName): DbSet
  • GetStatement(): PDOStatement, GetConnection(): PDO
  • Tracker(): ChangeTracker, GetSqlProvider(): IProviderSql
  • GetDbType(): string (abstract), IsDbType(string $dbType): bool
  • SaveChanges(): int, Execute(SqlCommand $cmd): PDOStatement
  • BigTransaction(callable $callback): void

Provider Implementations

  • SqliteContext::__construct(string $database), GetDbType(): string
  • MysqlContext::__construct(string $database, string $username, string $password, string $host = "127.0.0.1", int $port = 3306, $charset = "utf8mb4")

DbSet

DafDb\Query\DbSet | DafPhpFramwork/DafDb/Query/DbSet.php

  • __construct(Context $context)
  • GetTableInfo(): TableInfo, Execute(SqlCommand $cmd): PDOStatement, GetLastInsertedId(): bool|string
  • Add(object|array $data): object
  • Update(object|array $data, callable $func = null): void
  • Remove(callable|array|object $objOrfunc), Clear(): void

Queryable (Fluent Query API)

DafDb\Query\Queryable | DafPhpFramwork/DafDb/Query/Queryable.php

  • FirstOrDefault, SingleOrDefault, Where, OrderBy, OrderByDescending
  • Skip, Take, Any, Count, Map, ForEach
  • Include, ThenInclude, RowToArray, ToArray, ToCollection
  • Protected fetch pipeline: Fetch, FetchAll

Migrations

  • Migrations::Migrate(DbContext $dbContext, string $appFolder)
  • Migrations::Rollback(DbContext $dbContext, string $appFolder)
  • Migrations::Generate(DbContext $dbContext, string $migrationName, string $appFolder)
  • Migration abstract hooks: Up(MigrationBuilder $migrationBuilder), Down(MigrationBuilder $migrationBuilder)
  • MigrationBuilder: CreateTable, DropTable, AlterTable, Sql, GetChanges

Usage Example

PHP
<?php
$users = $context->Users
    ->Where(fn($u) => $u->IsActive)
    ->OrderBy(fn($u) => $u->LastName)
    ->Take(50)
    ->ToArray();

$context->Users->Add(new UserModel(["Name" => "Doron"]));
$context->SaveChanges();