first commit
This commit is contained in:
49
app/Model/postModel.php
Normal file
49
app/Model/postModel.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
namespace Blog\Model;
|
||||
|
||||
use Blog\Entity\post;
|
||||
use Blog\Database\database;
|
||||
use Exception;
|
||||
|
||||
class PostModel {
|
||||
private $db;
|
||||
|
||||
public function __construct() {
|
||||
$this->db = Database::getConnection();
|
||||
}
|
||||
|
||||
public function getPosts(): array {
|
||||
$posts = [];
|
||||
$query = $this->db->query(<<<SQL
|
||||
SELECT p.id, u.username, p.title, p.content, p.stamp
|
||||
FROM posts p
|
||||
JOIN users u ON u.id = p.author_id
|
||||
SQL);
|
||||
|
||||
if(!$query->rowCount())
|
||||
throw new Exception("no entries available");
|
||||
|
||||
while($row = $query->fetchObject()) {
|
||||
$posts[] = new Post($row->id, $row->title, $row->content, $row->username, $row->stamp);
|
||||
}
|
||||
return $posts;
|
||||
}
|
||||
|
||||
public function getPost($id): ?Post {
|
||||
$query = $this->db->prepare(<<<SQL
|
||||
SELECT p.id, u.username, p.title, p.content, p.stamp
|
||||
FROM posts p
|
||||
JOIN users u ON u.id = p.author_id
|
||||
WHERE p.id = :id
|
||||
LIMIT 1
|
||||
SQL);
|
||||
$query->bindParam(":id", $id, $this->db::PARAM_INT);
|
||||
$query->execute();
|
||||
|
||||
if(!$query->rowCount())
|
||||
throw new Exception("no entry found");
|
||||
|
||||
$row = $query->fetchObject();
|
||||
return new Post($row->id, $row->title, $row->content, $row->username, $row->stamp);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user