Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- как мне увидеть на примере это кода как это работает. Я запускаю, но пустая страница выходит
- Листинг 23.13. Статические страницы. Файл pages/StaticPage.php
- <?php ## Статические страницы
- require_once "Cached.php";
- class StaticPage extends Cached
- {
- // Конструктор класса
- public function __construct($id)
- {
- // Проверяем нет ли такой страницы в кэше
- if ($this->isCached($this->id($id))) {
- // Есть, инициализируем объект содержимым кэша
- parent::__construct($this->title(), $this->content());
- } else {
- // Данные пока не кэшированы, извлекаем
- // содержимое из базы данных
- $query = "SELECT * FROM static_pages WHERE id = :id LIMIT 1";
- $sth = $dbh->prepare($query);
- $sth = $dbh->execute($query, [$id]);
- $page = $sth->fetch(PDO::FETCH_ASSOC);
- parent::__construct($page['title'], $page['title']);
- parent::__construct("Контакты", "Содержимое страницы Контакты");
- }
- }
- // Уникальный ключ для кэша
- public function id($name)
- {
- return "static_page_{$name}";
- }
- }
- ?>
- Листинг 23.12. Базовый класс для кэшируемых страниц. Файл pages/Cached.php
- <?php ## Базовый класс для кэшируемых страниц
- require_once "Page.php";
- class Cached extends Page
- {
- // Время действия кэша
- protected $expires;
- // Хранилище
- protected $store;
- // Конструктор класса
- public function __construct($title = '', $content = '', $expires = 0)
- {
- // Вызываем конструктор базового класса Page
- parent::__construct($title, $content);
- // Устанавливаем время жизни кэша
- $this->expires = $expires;
- // Подготовка хранилища
- // $this->store = new Memcached();
- // $this->store->addServer('localhost', 11211);
- // Размещение данных в хранилище
- $this->set($this->id('title'), $title);
- $this->set($this->id('content'), $content);
- }
- // Проверить есть ли позиция $key в кэше
- protected function isCached($key)
- {
- // return (bool) $this->store->get($key);
- }
- // Поместить в кэш по ключу $key значение $value
- // В случае если ключ уже существует:
- // 1. Не делать ничего, если $force принимает значение false
- // 2. Переписать, если $force принимает значение true
- protected function set($key, $value, $force = false)
- {
- // if ($force) {
- // $this->store->set($key, $value, $this->expires);
- // } else {
- // if($this->isCached($key)) {
- // $this->store->set($key, $value, $this->expires);
- // }
- // }
- }
- // Извлечение значения $key из кэша
- protected function get($key)
- {
- // return $this->store->get($key);
- }
- // Формируем уникальный ключ для хранилища
- public function id($name)
- {
- die("Что здесь делать? Неизвестно!");
- }
- // Получение заголовка страницы
- public final function title()
- {
- // if ($this->isCached($this->id('title'))) {
- // return $this->get($this->id('title'));
- // } else {
- return parent::title();
- // }
- }
- // Получение содержимое страницы
- public final function content()
- {
- // if ($this->isCached($this->id('content'))) {
- // return $this->get($this->id('content'));
- // } else {
- return parent::content();
- // }
- }
- }
- ?>
- Page.php
- <?php ## Базовый класс страницы
- class Page
- {
- // Любая страница имеет заголовок
- protected $title;
- // И содержимое
- protected $content;
- // Конструктор класса
- public function __construct($title = '', $content = '')
- {
- $this->title = $title;
- $this->content = $content;
- }
- // Получение заголовка страницы
- public function title()
- {
- return $this->title;
- }
- // Получение содержимого страницы
- public function content()
- {
- return $this->content;
- }
- // Формирование HTML-представления страницы
- public function render()
- {
- echo "<h1>".htmlspecialchars($this->title())."</h1>";
- echo "</p>".nl2br(htmlspecialchars($this->content()))."</p>";
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment