Creating Database Abstraction
Database abstraction is a design approach that separates the details of database access, such as SQL queries, from the main application logic by providing a set of reusable methods or interfaces for interacting with the database.
When you use database abstraction in your application, you hide the specific SQL statements and low-level database interactions behind a set of reusable methods. This means you do not have to write raw SQL every time you want to perform a database operation. Instead, you call methods like find, save, or delete, which handle the underlying SQL for you. This approach makes your code cleaner, more maintainable, and easier to reuse across different parts of your application.
Database.php
123456789101112131415161718192021222324252627282930313233343536373839404142<?php class Database { protected $pdo; public function __construct($dsn, $username, $password) { $this->pdo = new PDO($dsn, $username, $password); } public function find($table, $conditions = []) { $sql = "SELECT * FROM {$table}"; if (!empty($conditions)) { $fields = []; foreach ($conditions as $column => $value) { $fields[] = "{$column} = :{$column}"; } $sql .= " WHERE " . implode(' AND ', $fields); } $stmt = $this->pdo->prepare($sql); foreach ($conditions as $column => $value) { $stmt->bindValue(":{$column}", $value); } $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } public function save($table, $data) { $columns = array_keys($data); $fields = implode(', ', $columns); $placeholders = ':' . implode(', :', $columns); $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"; $stmt = $this->pdo->prepare($sql); foreach ($data as $column => $value) { $stmt->bindValue(":{$column}", $value); } return $stmt->execute(); } }
By introducing methods like find and save, you can avoid repetitive SQL code in every model. Instead, your models can focus on business logic and simply call these generic methods to perform database operations. This makes your model code much easier to read and maintain, since the details of constructing queries and managing parameters are handled in one place.
User.php
12345678910111213141516171819<?php require_once 'Database.php'; class User extends Database { protected $table = 'users'; public function findByEmail($email) { $result = $this->find($this->table, ['email' => $email]); return $result ? $result[0] : null; } public function saveUser($data) { return $this->save($this->table, $data); } }
Using database abstraction means you can easily change how your application interacts with the database in the future, such as switching to a different database system or adding new features, without rewriting all your models. It also makes testing easier, since you can mock or stub the database layer. This level of separation leads to cleaner, more flexible, and more maintainable code as your application grows.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Awesome!
Completion rate improved to 6.67
Creating Database Abstraction
Pyyhkäise näyttääksesi valikon
Database abstraction is a design approach that separates the details of database access, such as SQL queries, from the main application logic by providing a set of reusable methods or interfaces for interacting with the database.
When you use database abstraction in your application, you hide the specific SQL statements and low-level database interactions behind a set of reusable methods. This means you do not have to write raw SQL every time you want to perform a database operation. Instead, you call methods like find, save, or delete, which handle the underlying SQL for you. This approach makes your code cleaner, more maintainable, and easier to reuse across different parts of your application.
Database.php
123456789101112131415161718192021222324252627282930313233343536373839404142<?php class Database { protected $pdo; public function __construct($dsn, $username, $password) { $this->pdo = new PDO($dsn, $username, $password); } public function find($table, $conditions = []) { $sql = "SELECT * FROM {$table}"; if (!empty($conditions)) { $fields = []; foreach ($conditions as $column => $value) { $fields[] = "{$column} = :{$column}"; } $sql .= " WHERE " . implode(' AND ', $fields); } $stmt = $this->pdo->prepare($sql); foreach ($conditions as $column => $value) { $stmt->bindValue(":{$column}", $value); } $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } public function save($table, $data) { $columns = array_keys($data); $fields = implode(', ', $columns); $placeholders = ':' . implode(', :', $columns); $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})"; $stmt = $this->pdo->prepare($sql); foreach ($data as $column => $value) { $stmt->bindValue(":{$column}", $value); } return $stmt->execute(); } }
By introducing methods like find and save, you can avoid repetitive SQL code in every model. Instead, your models can focus on business logic and simply call these generic methods to perform database operations. This makes your model code much easier to read and maintain, since the details of constructing queries and managing parameters are handled in one place.
User.php
12345678910111213141516171819<?php require_once 'Database.php'; class User extends Database { protected $table = 'users'; public function findByEmail($email) { $result = $this->find($this->table, ['email' => $email]); return $result ? $result[0] : null; } public function saveUser($data) { return $this->save($this->table, $data); } }
Using database abstraction means you can easily change how your application interacts with the database in the future, such as switching to a different database system or adding new features, without rewriting all your models. It also makes testing easier, since you can mock or stub the database layer. This level of separation leads to cleaner, more flexible, and more maintainable code as your application grows.
Kiitos palautteestasi!