. namespace hoplite\views; require_once HOPLITE_ROOT . '/views/cache_backend.php'; /*! An instance of CacheBackend that stores compiled templates in a database table accessed through a PDO object. */ class PDOCacheBackend implements CacheBackend { /*! @var \PDO The dat abase to use. */ protected $db = NULL; /*! @var \PDOStatement Used to query for cached templates. */ protected $fetch_statement = NULL; /*! @var \PDOStatement Used to insert new templates. */ protected $insert_statement = NULL; /*! @var \PDOStatement Used to expire out-of-date templates. */ protected $delete_statement = NULL; /*! @var string Base query for a multi-fetch operation. */ protected $fetch_multi_query = ""; /*! Constructor that prepares the database statements. @param \PDO The connected database object. @param string Name of the database table to store templates in. @param string Column in which the template name is stored. @param string Column in which the template data is stored. @param string Column in which the template last modified time is stored. */ public function __construct(\PDO $db, $table_name, $name_column_name = 'name', $data_column_name = 'template', $timestamp_column_name = 'timestamp') { $this->db = $db; $this->fetch_statement = $db->Prepare(" SELECT `$data_column_name` AS template, `$timestamp_column_name` AS timestamp FROM $table_name WHERE `$name_column_name` IN (:name) "); $this->insert_statement = $db->Prepare(" INSERT INTO `$table_name` (`$name_column_name`, `$data_column_name`, `$timestamp_column_name`) VALUES (:name, :template, :timestamp) "); $this->delete_statement = $db->Prepare(" DELETE FROM `$table_name` WHERE `$name_column_name` = :name "); $this->fetch_multi_query = " SELECT `$name_column_name` AS name, `$data_column_name` AS template, `$timestamp_column_name` AS timestamp FROM $table_name WHERE `$name_column_name` IN "; } public function GetTemplateDataForName($name, $modification_time) { $this->fetch_statement->Execute(array('name' => $name)); $tpl = $this->fetch_statement->FetchObject(); if (!$tpl) return NULL; if ($tpl->timestamp < $modification_time) { $this->delete_statement->Execute(array('name' => $name)); return NULL; } return $tpl->template; } public function StoreCompiledTemplate($name, $modification_time, $data) { $this->insert_statement->Execute(array( 'name' => $name, 'timestamp' => $modification_time, 'template' => $data, )); } public function GetMultipleTemplates(Array $fetch_templates) { $placeholders = array_fill(0, count($fetch_templates), '?'); $stmt = $this->db->Prepare($this->fetch_multi_query . '(' . implode(',', $placeholders) . ')'); $stmt->Execute(array_keys($fetch_templates)); $templates = array(); while (($template = $stmt->FetchObject())) { if ($template->timestamp >= $fetch_templates[$template->name]) $templates[$template->name] = $template->template; } return $templates; } }