resource.mysql.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * MySQL Resource
  4. *
  5. * Resource Implementation based on the Custom API to use
  6. * MySQL as the storage resource for Smarty's templates and configs.
  7. *
  8. * Table definition:
  9. * <pre>CREATE TABLE IF NOT EXISTS `templates` (
  10. * `name` varchar(100) NOT NULL,
  11. * `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  12. * `source` text,
  13. * PRIMARY KEY (`name`)
  14. * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
  15. *
  16. * Demo data:
  17. * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
  18. *
  19. * @package Resource-examples
  20. * @author Rodney Rehm
  21. */
  22. class Smarty_Resource_Mysql extends Smarty_Resource_Custom {
  23. // PDO instance
  24. protected $db;
  25. // prepared fetch() statement
  26. protected $fetch;
  27. // prepared fetchTimestamp() statement
  28. protected $mtime;
  29. public function __construct() {
  30. try {
  31. $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
  32. } catch (PDOException $e) {
  33. throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
  34. }
  35. $this->fetch = $this->db->prepare('SELECT modified, source FROM templates WHERE name = :name');
  36. $this->mtime = $this->db->prepare('SELECT modified FROM templates WHERE name = :name');
  37. }
  38. /**
  39. * Fetch a template and its modification time from database
  40. *
  41. * @param string $name template name
  42. * @param string $source template source
  43. * @param integer $mtime template modification timestamp (epoch)
  44. * @return void
  45. */
  46. protected function fetch($name, &$source, &$mtime)
  47. {
  48. $this->fetch->execute(array('name' => $name));
  49. $row = $this->fetch->fetch();
  50. $this->fetch->closeCursor();
  51. if ($row) {
  52. $source = $row['source'];
  53. $mtime = strtotime($row['modified']);
  54. } else {
  55. $source = null;
  56. $mtime = null;
  57. }
  58. }
  59. /**
  60. * Fetch a template's modification time from database
  61. *
  62. * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source.
  63. * @param string $name template name
  64. * @return integer timestamp (epoch) the template was modified
  65. */
  66. protected function fetchTimestamp($name) {
  67. $this->mtime->execute(array('name' => $name));
  68. $mtime = $this->mtime->fetchColumn();
  69. $this->mtime->closeCursor();
  70. return strtotime($mtime);
  71. }
  72. }