Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Creating Database Abstraction | Models
PHP MVC Development

bookCreating Database Abstraction

Note
Definition

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

Database.php

copy
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

User.php

copy
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.

question mark

What is a key benefit of database abstraction in MVC?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Suggested prompts:

Can you give examples of how to implement database abstraction in code?

What are some popular libraries or frameworks that provide database abstraction?

Are there any drawbacks to using database abstraction layers?

bookCreating Database Abstraction

Deslize para mostrar o menu

Note
Definition

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

Database.php

copy
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

User.php

copy
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.

question mark

What is a key benefit of database abstraction in MVC?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3
some-alt