DLight\Application\DB

Mô tả: lớp DB là “proxy” kế thừa DLight\Database\DatabaseManager. Tùy theo env('DB_DESIGN') mà các method fluent sẽ được forward tới: builder (Query Builder) hoặc mapper (CRUD/Mapper).

Namespace / đăng ký

  • Namespace: DLight\Application
  • File: src/Application/DB.php
  • Đăng ký: Composer PSR-4 (DLight\src/)

Public API rõ ràng

  • __construct() (nếu class con có $table thì auto set mapper cho table đó)
  • DB::table(string $table): self
  • DB::mapper(): self (ép dùng “mapper design”)
  • $db->builder(): self (chuyển sang “builder design”)
  • $db->getAdapter() (trả về adapter đang dùng)
  • __call(), __callStatic(): forward method sang mapper/builder (nếu sai design sẽ throw CallWrongMethodOnDbDesign)

Cách dùng + demo

Chọn table bằng static:

use DLight\Application\DB;

$users = DB::table('users')->all();

Ép dùng mapper (không phụ thuộc DB_DESIGN):

use DLight\Application\DB;

$user = DB::mapper()->table('users')->find(1);

Lấy adapter để query raw:

use DLight\Application\DB;

$db = new DB();
$adapter = $db->getAdapter();

$res = $adapter->query('SELECT 1 AS ok');
$row = $adapter->fetch($res);

Ghi chú

  • Soft delete: nếu class con kế thừa DB và dùng trait DLight\Database\Traits\SoftDelete, mapper sẽ được tạo với soft-delete tự động.
  • Method available: rất nhiều method “động” phụ thuộc vào Mapper/Builder; khi gọi sai design sẽ ném lỗi CallWrongMethodOnDbDesign.