Model.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: root
  5. * Date: 31.07.18
  6. * Time: 10:49
  7. */
  8. require_once "DB.php";
  9. require_once "Author.php";
  10. require_once "Book.php";
  11. require_once "User.php";
  12. abstract class Model
  13. {
  14. public static $table;
  15. public static $fields;
  16. public static $pk;
  17. public $connection;
  18. public function __construct()
  19. {
  20. $this->connection = DB::getConnection();
  21. }
  22. public function getByPk($id): array
  23. {
  24. $query =
  25. "SELECT " . implode(self::$fields, ", ") .
  26. " FROM " . self::$table .
  27. " WHERE " . self::$pk . " = " . $id;
  28. return $this->connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
  29. }
  30. public function getAllRows(): array
  31. {
  32. $query =
  33. "SELECT * FROM " . self::$table;
  34. return $this->connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
  35. }
  36. public function getRowsByField(array $fields): array
  37. {
  38. $query =
  39. "SELECT `" . implode("`, `", $fields) . "`" .
  40. " FROM " . self::$table;
  41. return $this->connection->query($query)->fetchAll(PDO::FETCH_ASSOC);
  42. }
  43. public function deleteRow(string $condition): void
  44. {
  45. $query =
  46. "DELETE FROM " . self::$table .
  47. " WHERE " . $condition;
  48. $this->connection->exec($query);
  49. }
  50. public function updateRow(string $targetSet, string $condition): void
  51. {
  52. $query =
  53. "UPDATE " . self::$table .
  54. " SET " . $targetSet .
  55. " WHERE " . $condition;
  56. $this->connection->exec($query);
  57. }
  58. }