写一段MVC模式中模型层的代码
时间: 2024-02-03 09:13:00 浏览: 58
一个简单的MVC模式实例
4星 · 用户满意度95%
假设我们正在开发一个简单的博客应用程序,以下是一个可能的模型层代码示例:
```php
class PostModel {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getPosts() {
$query = "SELECT * FROM posts";
$result = $this->db->query($query);
return $result->fetchAll();
}
public function getPostById($id) {
$query = "SELECT * FROM posts WHERE id = :id";
$statement = $this->db->prepare($query);
$statement->execute(['id' => $id]);
return $statement->fetch();
}
public function createPost($title, $content) {
$query = "INSERT INTO posts (title, content) VALUES (:title, :content)";
$statement = $this->db->prepare($query);
$statement->execute(['title' => $title, 'content' => $content]);
return $this->db->lastInsertId();
}
public function updatePost($id, $title, $content) {
$query = "UPDATE posts SET title = :title, content = :content WHERE id = :id";
$statement = $this->db->prepare($query);
$statement->execute(['id' => $id, 'title' => $title, 'content' => $content]);
return $statement->rowCount();
}
public function deletePost($id) {
$query = "DELETE FROM posts WHERE id = :id";
$statement = $this->db->prepare($query);
$statement->execute(['id' => $id]);
return $statement->rowCount();
}
}
```
这个模型层使用了 PDO 来与数据库进行交互,实现了一些基本的增删改查操作。在一个真正的应用程序中,可能会有更多的方法和复杂的查询逻辑,但这个示例应该可以帮助你理解模型层是如何工作的。
阅读全文