Kotchasan Framework Documentation
DriverInterface
DriverInterface
Overview
Kotchasan\Connection\DriverInterface is the interface that defines the standard for all database drivers in the Kotchasan system. It enables easy creation of new drivers or customization of existing ones.
Usage
Creating a New Driver
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
{
// Kotchasan\Database connection code
try {
// Kotchasan\Database connection
$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;
}
// Implement other methods according to interface
}Required Methods
Connection Management
connect(array $config): bool
Connect to database using provided configuration
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
Close database connection
class ExampleClass {
<?php
public function disconnect(): bool
{
$this->pdo = null;
return true;
}
}isConnected(): bool
Check connection status
class ExampleClass {
<?php
public function isConnected(): bool
{
return $this->pdo !== null;
}
}Statement Management
prepare(string $query): StatementInterface
Prepare SQL statement for execution
class ExampleClass {
<?php
public function prepare(string $query): StatementInterface
{
if (!$this->isConnected()) {
throw new Kotchasan\DatabaseException("Not connected to database");
}
try {
$pdoStatement = $this->pdo->prepare($query);
return new PDOStatement($pdoStatement);
} catch (\PDOException $e) {
throw new Kotchasan\DatabaseException("Failed to prepare statement: " . $e->getMessage());
}
}
}Transaction Management
beginTransaction(): bool
Start 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
Commit 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
Rollback 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
Check if currently in transaction
class ExampleClass {
<?php
public function inTransaction(): bool
{
if (!$this->isConnected()) {
return false;
}
return $this->pdo->inTransaction();
}
}Other Methods
lastInsertId(?string $name = null): string
Get ID of last inserted row
class ExampleClass {
<?php
public function lastInsertId(?string $name = null): string
{
if (!$this->isConnected()) {
return '';
}
return $this->pdo->lastInsertId($name);
}
}getLastError(): ?string
Get last error
class ExampleClass {
<?php
public function getLastError(): ?string
{
return $this->lastError;
}
}escape(string $value): string
Prevent SQL injection
class ExampleClass {
<?php
public function escape(string $value): string
{
if (!$this->isConnected()) {
throw new Kotchasan\DatabaseException("Not connected to database");
}
return $this->pdo->quote($value);
}
}getName(): string
Get driver name
class ExampleClass {
<?php
public function getName(): string
{
return 'custom'; // Driver name
}
}Advanced Methods
emptyTable(string $tableName, array $options = []): bool
Delete all data from table
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) {
// Fall back to 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
Optimize table
class ExampleClass {
<?php
public function optimizeTable(string $tableName): bool
{
// Kotchasan\Database-specific code
// 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
Format SQL function for database compatibility
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;
// Add other functions
default:
throw new \InvalidArgumentException("Unsupported SQL function: {$type}");
}
}
}Complete Driver Example
MongoDB Driver (Example)
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';
// Test connection
$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
{
// Create MongoDB statement wrapper
return new MongoDBStatement($this->client, $this->database, $query);
}
public function getName(): string
{
return 'mongodb';
}
// Implement other methods according to 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}";
}
}Registering New Driver
Using with ConnectionManager
use Kotchasan\Connection\ConnectionManager;
$config = [
'mongodb_main' => [
'driver' => 'mongodb',
'host' => 'localhost',
'port' => 27017,
'database' => 'myapp',
'username' => 'user',
'password' => 'pass'
]
];
$manager = new ConnectionManager($config);
// Register new driver
$manager->registerDriver('mongodb', MongoDBDriver::class);
// Use new driver
$connection = $manager->getConnection('mongodb_main');Best Practices and Considerations
Best Practices
- Include Error Handling: Handle errors appropriately
- Check Connection: Verify connection status before operations
- Use Prepared Statements: Prevent SQL injection
- Handle Transactions: Support transactions correctly
Considerations
- Compatibility: Check compatibility with target database
- Performance: Write efficient code
- Memory Management: Close connections when not needed
Common Issues
- Missing Methods: Must implement all interface methods
- Error Handling: Must handle errors appropriately
- Testing: Test driver thoroughly for all features
Related Classes
- Connection - Connection class
- ConnectionManager - Connection manager
- MySQLDriver - MySQL driver
- PostgreSQLDriver - PostgreSQL driver
- MSSQLDriver - SQL Server driver
- SQLiteDriver - SQLite driver