* @package ModFrog */ // WBClass::load('Airclip'); /** * Multi Purpose Counter INSERT INTO wbcounter (namespace,changed,counter) VALUES ("foobar",now(),1) ON DUPLICATE KEY UPDATE counter=counter+1, changed=now(); * * @version 1.0.0 * @package ModFrog */ class WBDatasource_Counter extends WBStdClass { /** * @const table name */ const TABLE_COUNTER = 'counter'; /** * database connection * @var WBDatasource_SQL */ private $db; /** * table configuration * @var array */ private $config = array(); /** * Constructor * * @param array $parameter */ final public function __construct($parameter = array()) { $config = WBClass::create('WBConfig'); $config->load('table'); $this->config = $config->get(self::TABLE_COUNTER); $this->db = WBClass::create( 'WBDatasource_SQL', $parameter ); } /** * Get Current Counter * * Fetch current counter state * @param string $namespace * @return array */ public function get($namespace) { $cnt = array( 'counter' => 0, 'changed' => '0000-00-00 00:00:00' ); $namespace = trim(strtolower($namespace)); if (empty($namespace)) { return $cnt; } $namespace = $this->db->quote($namespace); $query = array('SELECT * FROM'); $query[] = $this->config['table']; $query[] = 'WHERE namespace=' . $namespace; $query = implode(' ', $query); $res = $this->db->query($query); while ($l = $res->fetch_assoc()) { $cnt = $l; break; } $res->free_result(); return $cnt; } /** * Set Counter Value * * Set namespace counter to specified positive value * * @param string $namespace * @param int $value */ public function set($namespace, $value) { $namespace = trim(strtolower($namespace)); if (empty($namespace)) { return; } $value = intval($value); if (0 > $value) { $value = 0; } $value = $this->db->quote($value); $namespace = $this->db->quote($namespace); $query = array('INSERT INTO'); $query[] = $this->config['table']; $query[] = '(namespace,changed,counter)'; $query[] = 'VALUES('. $namespace .', now(), '. $value .')'; $query[] = 'ON DUPLICATE KEY UPDATE counter=' . $value . ', changed=now()'; $query = implode(' ', $query); $this->db->query($query); } /** * Increment Counter Value * * Add increment value - default 1 - to counter. * * @param string $namespace * @param int $value (1) */ public function inc($namespace, $value = 1) { $namespace = trim(strtolower($namespace)); if (empty($namespace)) { return; } $value = intval($value); if (0 > $value) { return; } $value = $this->db->quote($value); $namespace = $this->db->quote($namespace); $query = array('INSERT INTO'); $query[] = $this->config['table']; $query[] = '(namespace,changed,counter)'; $query[] = 'VALUES('. $namespace .', now(), '. $value .')'; $query[] = 'ON DUPLICATE KEY UPDATE counter=counter + ' . $value . ', changed=now()'; $query = implode(' ', $query); $this->db->query($query); } }