phpist

Untitled

Oct 25th, 2019
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.13 KB | None | 0 0
  1. как мне увидеть на примере это кода как это работает. Я запускаю, но пустая страница выходит
  2.  
  3.  
  4. Листинг 23.13. Статические страницы. Файл pages/StaticPage.php
  5. <?php ## Статические страницы
  6. require_once "Cached.php";
  7. class StaticPage extends Cached
  8. {
  9. // Конструктор класса
  10. public function __construct($id)
  11. {
  12. // Проверяем нет ли такой страницы в кэше
  13. if ($this->isCached($this->id($id))) {
  14. // Есть, инициализируем объект содержимым кэша
  15. parent::__construct($this->title(), $this->content());
  16. } else {
  17. // Данные пока не кэшированы, извлекаем
  18. // содержимое из базы данных
  19. $query = "SELECT * FROM static_pages WHERE id = :id LIMIT 1";
  20. $sth = $dbh->prepare($query);
  21. $sth = $dbh->execute($query, [$id]);
  22. $page = $sth->fetch(PDO::FETCH_ASSOC);
  23. parent::__construct($page['title'], $page['title']);
  24. parent::__construct("Контакты", "Содержимое страницы Контакты");
  25. }
  26. }
  27.  
  28. // Уникальный ключ для кэша
  29. public function id($name)
  30. {
  31. return "static_page_{$name}";
  32. }
  33. }
  34. ?>
  35.  
  36. Листинг 23.12. Базовый класс для кэшируемых страниц. Файл pages/Cached.php
  37. <?php ## Базовый класс для кэшируемых страниц
  38. require_once "Page.php";
  39. class Cached extends Page
  40. {
  41. // Время действия кэша
  42. protected $expires;
  43. // Хранилище
  44. protected $store;
  45.  
  46. // Конструктор класса
  47. public function __construct($title = '', $content = '', $expires = 0)
  48. {
  49. // Вызываем конструктор базового класса Page
  50. parent::__construct($title, $content);
  51. // Устанавливаем время жизни кэша
  52. $this->expires = $expires;
  53. // Подготовка хранилища
  54. // $this->store = new Memcached();
  55. // $this->store->addServer('localhost', 11211);
  56. // Размещение данных в хранилище
  57. $this->set($this->id('title'), $title);
  58. $this->set($this->id('content'), $content);
  59. }
  60.  
  61. // Проверить есть ли позиция $key в кэше
  62. protected function isCached($key)
  63. {
  64. // return (bool) $this->store->get($key);
  65. }
  66. // Поместить в кэш по ключу $key значение $value
  67. // В случае если ключ уже существует:
  68. // 1. Не делать ничего, если $force принимает значение false
  69. // 2. Переписать, если $force принимает значение true
  70. protected function set($key, $value, $force = false)
  71. {
  72. // if ($force) {
  73. // $this->store->set($key, $value, $this->expires);
  74. // } else {
  75. // if($this->isCached($key)) {
  76. // $this->store->set($key, $value, $this->expires);
  77. // }
  78. // }
  79. }
  80. // Извлечение значения $key из кэша
  81. protected function get($key)
  82. {
  83. // return $this->store->get($key);
  84. }
  85.  
  86. // Формируем уникальный ключ для хранилища
  87. public function id($name)
  88. {
  89. die("Что здесь делать? Неизвестно!");
  90. }
  91.  
  92. // Получение заголовка страницы
  93. public final function title()
  94. {
  95. // if ($this->isCached($this->id('title'))) {
  96. // return $this->get($this->id('title'));
  97. // } else {
  98. return parent::title();
  99. // }
  100. }
  101. // Получение содержимое страницы
  102. public final function content()
  103. {
  104. // if ($this->isCached($this->id('content'))) {
  105. // return $this->get($this->id('content'));
  106. // } else {
  107. return parent::content();
  108. // }
  109. }
  110. }
  111. ?>
  112.  
  113.  
  114. Page.php
  115.  
  116. <?php ## Базовый класс страницы
  117. class Page
  118. {
  119. // Любая страница имеет заголовок
  120. protected $title;
  121. // И содержимое
  122. protected $content;
  123. // Конструктор класса
  124. public function __construct($title = '', $content = '')
  125. {
  126. $this->title = $title;
  127. $this->content = $content;
  128. }
  129. // Получение заголовка страницы
  130. public function title()
  131. {
  132. return $this->title;
  133. }
  134. // Получение содержимого страницы
  135. public function content()
  136. {
  137. return $this->content;
  138. }
  139. // Формирование HTML-представления страницы
  140. public function render()
  141. {
  142. echo "<h1>".htmlspecialchars($this->title())."</h1>";
  143. echo "</p>".nl2br(htmlspecialchars($this->content()))."</p>";
  144. }
  145. }
  146. ?>
Advertisement
Add Comment
Please, Sign In to add comment