Kotchasan Framework Documentation

Kotchasan Framework Documentation

DriverInterface

TH 05 Feb 2026 06:23

DriverInterface

ภาพรวม

Kotchasan\Connection\DriverInterface เป็นอินเทอร์เฟซที่กำหนดมาตรฐานสำหรับไดรเวอร์ฐานข้อมูลทั้งหมดในระบบ Kotchasan ทำให้สามารถสร้างไดรเวอร์ใหม่หรือปรับแต่งไดรเวอร์ที่มีอยู่ได้อย่างง่ายดาย

การใช้งาน

การสร้างไดรเวอร์ใหม่

use Kotchasan\Connection\DriverInterface;
use Kotchasan\Execution\StatementInterface;

class CustomDriver implements DriverInterface
{
    private $connection = null;
    private ?string $lastError = null;

    public function connect(array $config): bool
    {
        // ใส่โค้ดการเชื่อมต่อฐานข้อมูล
        try {
            // การเชื่อมต่อฐานข้อมูล
            $this->connection = new CustomKotchasan\DatabaseConnection($config);
            return true;
        } catch (\Exception $e) {
            $this->lastError = $e->getMessage();
            return false;
        }
    }

    public function disconnect(): bool
    {
        $this->connection = null;
        return true;
    }

    public function isConnected(): bool
    {
        return $this->connection !== null;
    }

    // ใส่เมธอดอื่นๆ ตาม interface
}

เมธอดที่จำเป็น

การจัดการการเชื่อมต่อ

connect(array $config): bool

เชื่อมต่อกับฐานข้อมูลโดยใช้การตั้งค่าที่กำหนด

class ExampleClass {
    <?php
public function connect(array $config): bool
{
    $dsn = $this->buildDsn($config);

    try {
        $this->pdo = new \PDO(
            $dsn,
            $config['username'] ?? '',
            $config['password'] ?? '',
            $this->getDefaultOptions()
        );
        return true;
    } catch (\PDOException $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

disconnect(): bool

ปิดการเชื่อมต่อฐานข้อมูล

class ExampleClass {
    <?php
public function disconnect(): bool
{
    $this->pdo = null;
    return true;
}
}

isConnected(): bool

ตรวจสอบสถานะการเชื่อมต่อ

class ExampleClass {
    <?php
public function isConnected(): bool
{
    return $this->pdo !== null;
}
}

การจัดการ Statement

prepare(string $query): StatementInterface

เตรียม SQL statement สำหรับการ execute

class ExampleClass {
    <?php
public function prepare(string $query): StatementInterface
{
    if (!$this->isConnected()) {
        throw new Kotchasan\DatabaseException("ไม่ได้เชื่อมต่อกับฐานข้อมูล");
    }

    try {
        $pdoStatement = $this->pdo->prepare($query);
        return new PDOStatement($pdoStatement);
    } catch (\PDOException $e) {
        throw new Kotchasan\DatabaseException("ไม่สามารถเตรียม statement: " . $e->getMessage());
    }
}
}

การจัดการ Transaction

beginTransaction(): bool

เริ่มต้น transaction

class ExampleClass {
    <?php
public function beginTransaction(): bool
{
    if (!$this->isConnected()) {
        return false;
    }

    try {
        return $this->pdo->beginTransaction();
    } catch (\PDOException $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

commit(): bool

ยืนยัน transaction

class ExampleClass {
    <?php
public function commit(): bool
{
    if (!$this->isConnected()) {
        return false;
    }

    try {
        return $this->pdo->commit();
    } catch (\PDOException $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

rollback(): bool

ยกเลิก transaction

class ExampleClass {
    <?php
public function rollback(): bool
{
    if (!$this->isConnected()) {
        return false;
    }

    try {
        return $this->pdo->rollBack();
    } catch (\PDOException $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

inTransaction(): bool

ตรวจสอบว่ากำลังอยู่ใน transaction หรือไม่

class ExampleClass {
    <?php
public function inTransaction(): bool
{
    if (!$this->isConnected()) {
        return false;
    }

    return $this->pdo->inTransaction();
}
}

เมธอดอื่นๆ

lastInsertId(?string $name = null): string

ดึง ID ของแถวที่เพิ่มล่าสุด

class ExampleClass {
    <?php
public function lastInsertId(?string $name = null): string
{
    if (!$this->isConnected()) {
        return '';
    }

    return $this->pdo->lastInsertId($name);
}
}

getLastError(): ?string

ดึงข้อผิดพลาดล่าสุด

class ExampleClass {
    <?php
public function getLastError(): ?string
{
    return $this->lastError;
}
}

escape(string $value): string

ป้องกัน SQL injection

class ExampleClass {
    <?php
public function escape(string $value): string
{
    if (!$this->isConnected()) {
        throw new Kotchasan\DatabaseException("ไม่ได้เชื่อมต่อกับฐานข้อมูล");
    }

    return $this->pdo->quote($value);
}
}

getName(): string

ดึงชื่อไดรเวอร์

class ExampleClass {
    <?php
public function getName(): string
{
    return 'custom'; // ชื่อไดรเวอร์
}
}

เมธอดขั้นสูง

emptyTable(string $tableName, array $options = []): bool

ลบข้อมูลทั้งหมดในตาราง

class ExampleClass {
    <?php
public function emptyTable(string $tableName, array $options = []): bool
{
    $options = array_merge([
        'use_truncate' => true
    ], $options);

    $quotedTable = $this->quoteIdentifier($tableName);

    if ($options['use_truncate']) {
        try {
            $sql = "TRUNCATE TABLE {$quotedTable}";
            $statement = $this->prepare($sql);
            return $statement->execute() !== false;
        } catch (\Exception $e) {
            // ใช้ DELETE แทน
        }
    }

    try {
        $sql = "DELETE FROM {$quotedTable}";
        $statement = $this->prepare($sql);
        return $statement->execute() !== false;
    } catch (\Exception $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

optimizeTable(string $tableName): bool

เพิ่มประสิทธิภาพตาราง

class ExampleClass {
    <?php
public function optimizeTable(string $tableName): bool
{
    // ใส่โค้ดเฉพาะฐานข้อมูล
    // MySQL: OPTIMIZE TABLE
    // PostgreSQL: VACUUM
    // SQL Server: ALTER INDEX REBUILD
    // SQLite: VACUUM

    $quotedTable = $this->quoteIdentifier($tableName);

    try {
        $sql = $this->getOptimizeTableSql($quotedTable);
        $statement = $this->prepare($sql);
        return $statement->execute() !== false;
    } catch (\Exception $e) {
        $this->lastError = $e->getMessage();
        return false;
    }
}
}

formatSqlFunction(string $type, array $parameters, ?string $alias): string

จัดรูปแบบ SQL function ให้เข้ากันได้กับฐานข้อมูล

class ExampleClass {
    <?php
public function formatSqlFunction(string $type, array $parameters, ?string $alias): string
{
    $aliasStr = $alias ? ' AS ' . $this->quoteIdentifier($alias) : '';

    switch (strtoupper($type)) {
        case 'YEAR':
            return $this->formatYearFunction($parameters['column']) . $aliasStr;

        case 'CONCAT':
            return $this->formatConcatFunction($parameters['fields'], $parameters['separator'] ?? null) . $aliasStr;

        case 'NOW':
            return $this->formatNowFunction() . $aliasStr;

        // เพิ่มฟังก์ชันอื่นๆ

        default:
            throw new \InvalidArgumentException("ไม่รองรับ SQL function: {$type}");
    }
}
}

ตัวอย่างการสร้างไดรเวอร์ที่สมบูรณ์

ไดรเวอร์ MongoDB (ตัวอย่าง)

use Kotchasan\Connection\DriverInterface;
use Kotchasan\Execution\StatementInterface;
use MongoDB\Client;

class MongoDBDriver implements DriverInterface
{
    private ?Client $client = null;
    private ?string $database = null;
    private ?string $lastError = null;

    public function connect(array $config): bool
    {
        try {
            $uri = $this->buildUri($config);
            $this->client = new Client($uri);
            $this->database = $config['database'] ?? 'test';

            // ทดสอบการเชื่อมต่อ
            $this->client->selectKotchasan\Database($this->database)->command(['ping' => 1]);

            return true;
        } catch (\Exception $e) {
            $this->lastError = $e->getMessage();
            return false;
        }
    }

    public function disconnect(): bool
    {
        $this->client = null;
        $this->database = null;
        return true;
    }

    public function isConnected(): bool
    {
        return $this->client !== null;
    }

    public function prepare(string $query): StatementInterface
    {
        // สร้าง MongoDB statement wrapper
        return new MongoDBStatement($this->client, $this->database, $query);
    }

    public function getName(): string
    {
        return 'mongodb';
    }

    // ใส่เมธอดอื่นๆ ตาม interface

    private function buildUri(array $config): string
    {
        $host = $config['host'] ?? 'localhost';
        $port = $config['port'] ?? 27017;
        $username = $config['username'] ?? '';
        $password = $config['password'] ?? '';

        if ($username && $password) {
            return "mongodb://{$username}:{$password}@{$host}:{$port}";
        }

        return "mongodb://{$host}:{$port}";
    }
}

การลงทะเบียนไดรเวอร์ใหม่

การใช้งานกับ ConnectionManager

use Kotchasan\Connection\ConnectionManager;

$config = [
    'mongodb_main' => [
        'driver' => 'mongodb',
        'host' => 'localhost',
        'port' => 27017,
        'database' => 'myapp',
        'username' => 'user',
        'password' => 'pass'
    ]
];

$manager = new ConnectionManager($config);

// ลงทะเบียนไดรเวอร์ใหม่
$manager->registerDriver('mongodb', MongoDBDriver::class);

// ใช้งานไดรเวอร์ใหม่
$connection = $manager->getConnection('mongodb_main');

คำแนะนำและข้อควรระวัง

แนวทางปฏิบัติที่ดี

  1. ใส่ Error Handling: จัดการข้อผิดพลาดอย่างเหมาะสม
  2. ตรวจสอบการเชื่อมต่อ: ตรวจสอบสถานะก่อนทำงาน
  3. ใช้ Prepared Statements: ป้องกัน SQL injection
  4. จัดการ Transaction: รองรับ transaction อย่างถูกต้อง

ข้อควรระวัง

  1. ความเข้ากันได้: ตรวจสอบความเข้ากันได้กับฐานข้อมูล
  2. ประสิทธิภาพ: เขียนโค้ดให้มีประสิทธิภาพ
  3. การจัดการหน่วยความจำ: ปิดการเชื่อมต่อเมื่อไม่ใช้

ปัญหาที่พบบ่อย

  1. ไม่ได้ใส่เมธอดครบ: ต้องใส่เมธอดทั้งหมดตาม interface
  2. การจัดการข้อผิดพลาด: ต้องจัดการข้อผิดพลาดอย่างเหมาะสม
  3. การทดสอบ: ทดสอบไดรเวอร์ให้ครบทุกฟีเจอร์

คลาสที่เกี่ยวข้อง