resource.mysqls.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. * Note that this MySQL implementation fetches the source and timestamps in
  9. * a single database query, instead of two seperate like resource.mysql.php does.
  10. *
  11. * Table definition:
  12. * <pre>CREATE TABLE IF NOT EXISTS `templates` (
  13. * `name` varchar(100) NOT NULL,
  14. * `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  15. * `source` text,
  16. * PRIMARY KEY (`name`)
  17. * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre>
  18. *
  19. * Demo data:
  20. * <pre>INSERT INTO `templates` (`name`, `modified`, `source`) VALUES ('test.tpl', "2010-12-25 22:00:00", '{$x="hello world"}{$x}');</pre>
  21. *
  22. * @package Resource-examples
  23. * @author Rodney Rehm
  24. */
  25. class Smarty_Resource_Mysqls extends Smarty_Resource_Custom {
  26. // PDO instance
  27. protected $db;
  28. // prepared fetch() statement
  29. protected $fetch;
  30. public function __construct() {
  31. try {
  32. $this->db = new PDO("mysql:dbname=test;host=127.0.0.1", "smarty", "smarty");
  33. } catch (PDOException $e) {
  34. throw new SmartyException('Mysql Resource failed: ' . $e->getMessage());
  35. }
  36. $this->fetch = $this->db->prepare('SELECT modified, source 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. }