Author.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace App\Models;
  3. class Author
  4. {
  5. private $db;
  6. public function __construct()
  7. {
  8. $this->db = \App\Database::getInstance();
  9. }
  10. public function getAll()
  11. {
  12. $authors = $this->db->fetchAll("SELECT * FROM authors ORDER BY created_at DESC");
  13. foreach ($authors as &$author) {
  14. if (!empty($author['social_links'])) {
  15. $author['social_links'] = json_decode($author['social_links'], true);
  16. }
  17. }
  18. return $authors;
  19. }
  20. public function getById($id)
  21. {
  22. $author = $this->db->fetchOne("SELECT * FROM authors WHERE id = ?", [$id]);
  23. if ($author && !empty($author['social_links'])) {
  24. $author['social_links'] = json_decode($author['social_links'], true);
  25. }
  26. return $author;
  27. }
  28. public function create($data)
  29. {
  30. $socialLinks = '';
  31. if (isset($data['social_links']) && is_array($data['social_links'])) {
  32. $socialLinks = json_encode($data['social_links']);
  33. }
  34. $this->db->execute("
  35. INSERT INTO authors (name, image, description, social_links, created_at)
  36. VALUES (?, ?, ?, ?, datetime('now'))
  37. ", [
  38. $data['name'] ?? '',
  39. $data['image'] ?? '',
  40. $data['description'] ?? '',
  41. $socialLinks
  42. ]);
  43. return $this->db->lastInsertId();
  44. }
  45. public function update($id, $data)
  46. {
  47. $socialLinks = '';
  48. if (isset($data['social_links']) && is_array($data['social_links'])) {
  49. $socialLinks = json_encode($data['social_links']);
  50. }
  51. return $this->db->execute("
  52. UPDATE authors
  53. SET name = ?, image = ?, description = ?, social_links = ?, updated_at = datetime('now')
  54. WHERE id = ?
  55. ", [
  56. $data['name'] ?? '',
  57. $data['image'] ?? '',
  58. $data['description'] ?? '',
  59. $socialLinks,
  60. $id
  61. ]);
  62. }
  63. public function delete($id)
  64. {
  65. return $this->db->execute("DELETE FROM authors WHERE id = ?", [$id]);
  66. }
  67. public function search($query)
  68. {
  69. $searchTerm = '%' . $query . '%';
  70. $authors = $this->db->fetchAll("
  71. SELECT * FROM authors
  72. WHERE name LIKE ? OR description LIKE ?
  73. ORDER BY created_at DESC
  74. ", [$searchTerm, $searchTerm]);
  75. foreach ($authors as &$author) {
  76. if (!empty($author['social_links'])) {
  77. $author['social_links'] = json_decode($author['social_links'], true);
  78. }
  79. }
  80. return $authors;
  81. }
  82. }