/mvc/models/amazon
[return to app]1
<?php
2 /**
3 * Cache for the Amazon component
4 */
5 class amazonModel extends model {
6 /**
7 * Internal array of column names
8 *
9 * @var array
10 */
11 protected $_cols = array('supplyid', 'title', 'url', 'thumbnailsrc', 'thumbnailheight', 'thumbnailwidth');
12
13 /**
14 * Attempt to retrieve item data from cache
15 *
16 * @param mixed $items
17 * @return array
18 */
19 public function getCache($items) {
20 $titles = array();
21 $items = $this->db->cleanString($items);
22 $sql = 'select ' . implode(', ', $this->_cols) . ' from amazon_cache where supplyid'
23 . (!is_array($items) ? '=' . $items : ' in (' . implode(', ', $items) . ')')
24 . ' and lastupdate > (current_timestamp - interval 1 week) order by title';
25 $res = $this->db->query($sql);
26 if (!$res) {
27 $this->initializeDb();
28 $res = $this->db->query($sql);
29 }
30 while ($row = $res->fetch_assoc()) {
31 $thumb = array('src' => $row['thumbnailsrc'], 'height' => $row['thumbnailheight'],
32 'width' => $row['thumbnailwidth'], 'alt' => $row['title']);
33 $titles[$row['supplyid']] = array('title' => $row['title'], 'url' => $row['url'], 'thumbnail' =>
$thumb);
34 }
35 return $titles;
36 }
37
38 /**
39 * Insert or replace items in cache
40 *
41 * Uses MySQL/SQLite-specific replace-into syntax, other databases will need to adjust
42 *
43 * @param mixed $items
44 */
45 public function updateCache($items) {
46 foreach ($items as $supplyId => $properties) {
47 $properties = $this->db->cleanString($properties);
48 $sqlRecords[] = '(' . $this->db->cleanString($supplyId) . ', ' . $properties['title'] . ', '
49 . $properties['url'] . ', ' . $properties['thumbnail']['src'] . ', '
50 . $properties['thumbnail']['height'] . ', ' . $properties['thumbnail']['width']
51 . ', current_timestamp)';
52 }
53 if (isset($sqlRecords)) {
54 $sql = 'replace into amazon_cache (' . implode(', ', $this->_cols) . ', lastupdate) values '
55 . implode(', ', $sqlRecords);
56 $this->db->query($sql);
57 }
58 }
59
60 /**
61 * Automatically creates the database table for the cache
62 *
63 * Uses ISO-standard SQL syntax - performance would improve if you customize for your database, eg.:
64 * MySQL should change the "int(3)" columns to "tinyint(3) unsigned"
65 */
66 public function initializeDb() {
67 $sql = 'create table amazon_cache (
68 supplyid varchar(14) not null primary key,
69 title varchar(255) not null,
70 url varchar(255) not null,
71 thumbnailsrc varchar(255) null,
72 thumbnailheight int(3) null,
73 thumbnailwidth int(3) null,
74 lastupdate date not null,
75 index(lastupdate))';
76 $this->db->query($sql);
77 }
78 }