123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829 |
- <?php
- namespace KIF\Dao;
- use KIF\Exception\DaoException;
- use KIF\Verify;
- use KIF\Exception\ParamsException;
- use Exception;
- use KIF\Db\MySQLi;
- use KIF\Dao\SqlHelper;
- use KIF\Core\Config;
- use KIF\Cache\Memcached;
- use KIF\Math\Math;
- abstract class AbstractDao {
-
- protected $tableName;
-
- protected $primaryKey = 'id';
-
-
- private $useCache = false;
-
-
- private $cache_expiration = 3600;
-
-
- private $tableCacheFlag;
-
-
- private $memcacheClusterFlag;
-
- const PARAM_CREATE_ACTION_INSERT = 'INSERT INTO';
-
- const PARAM_CREATE_ACTION_INSERT_IGNORE = 'INSERT IGNORE';
-
- const PARAM_CREATE_ACTION_REPLACE = 'REPLACE INTO';
-
- const PARAM_CREATE_ACTION_ONDUPLICATE = 'ON DUPLICATE KEY UPDATE';
-
- protected $db;
-
-
- private $cluster_flag;
-
- public function __construct($cluster_flag = 'default') {
- $appConfig = Config::getInstance()->current();
- $dbConfig = $appConfig['db'];
-
- if (!$dbConfig || !isset($dbConfig[$cluster_flag]) || !is_string($dbConfig[$cluster_flag])) {
- throw new ParamsException("load config error:{$dbConfig}");
- }
- $this->cluster_flag = $cluster_flag;
-
- if (isset($appConfig['memcached']['dao_cache'])) {
- $this->memcacheClusterFlag = 'dao_cache';
- } elseif (isset($appConfig['memcached']['default'])) {
- $this->memcacheClusterFlag = 'default';
- } else {
- $this->useCache(false);
- }
- $dsn = $dbConfig[$cluster_flag];
- $this->db = new MySQLi($dsn);
- }
-
- public function getPrimaryKey() {
- return $this->primaryKey;
- }
-
- public function setTableName($tableName) {
- $this->tableName = $tableName;
- }
-
-
- public function useCache($useCache = true) {
- $this->useCache = (bool) $useCache;
- }
-
- public function parseCondition($condition = null) {
- if(empty($condition)) return '';
-
-
- if(is_string($condition)){
- return "
- WHERE ". $condition ." ";
- }
-
- if(!is_array($condition)){
- throw new Exception('parameter errors');
- }
- $condition = $this->quote($condition);
- $where = array();
- foreach($condition as $tmpK => $tmpV) {
-
-
-
-
-
-
-
-
-
-
-
-
- if (Verify::naturalNumber($tmpK)) {
- list($key, $val) = each($tmpV);
- } else {
- $key = $tmpK;
- $val = $tmpV;
- }
-
- if (strpos($key, '`') === false
- && strpos($key, '(') === false)
- {
- $key = "`{$key}`";
- }
- if(is_scalar($val)) {
- $where[] = "{$key} " . SqlHelper::explodeCompareOperator($val);
- } elseif(is_array($val)) {
- $where[] = "{$key} IN (".join(',', $val).")";
- } else {
- throw new Exception('parameter errors');
- }
- }
- return "
- WHERE ".join(' && ', $where)."
- ";
- }
-
- public function findIdsBy($condition = null, $limit = null, $order = null) {
- $result = $this->findBy($condition, $this->primaryKey, $limit, $this->primaryKey, $order);
- if (! $result) {
- return array();
- }
- return array_keys($result);
- }
-
- final public function findBy($condition = null, $returnAssociateKey = null, $limit = null, $selectCols = '*', $order = null) {
- $where = $this->parseCondition($condition);
- if (!isset($limit) || !preg_match('#^(?:\d+\s*,\s*)?\d+$#', $limit)) {
- $strLimit = ' ';
- } else {
- $strLimit = " LIMIT $limit ";
- }
- $strOrder = '';
- if(!empty($order)) {
- $strOrder = " ORDER BY {$order} ";
- }
- if(!isset($selectCols)) {
- $selectCols = '*';
- }
- $sql = "SELECT {$selectCols} FROM {$this->tableName}
- {$where}
- {$strOrder}
- {$strLimit}
- ;
- ";
- return $this->db->fetchAll($sql, $returnAssociateKey);
- }
- public function fetchOne($condition = null, $selectCols = '*', $order = null) {
- $result = self::findBy($condition, null, 1, $selectCols, $order);
- if (!$result) {
- return false;
- }
- return array_pop($result);
- }
-
- public function getsAll($order = null, $limit = null) {
- $ids = self::getsAllIds($order, $limit);
- return $this->gets($ids);
- }
-
- public function getsAllIds($order = null, $limit = null) {
- if (is_null($order)) {
- $order = "{$this->primaryKey} desc";
- }
- if (!is_string($order)) {
- throw new Exception('$order 必须是字符串或null');
- }
- $condition = null;
- $ids = self::findIdsBy($condition, $limit, $order);
- return $ids;
- }
-
- public function get($id) {
- if (Verify::int($id)) {
- if ($id < 1) {
- return false;
- }
- } elseif (is_string($id)) {
- if (strlen($id) == 0) {
- return false;
- }
- } else {
- return false;
- }
- $result = self::gets(array($id));
- if (!$result) {
- return false;
- }
- return array_pop($result);
- }
-
- public function gets(array $ids) {
- $return = array();
- if (empty($ids)) {
- return $return;
- }
- $ids = array_unique($ids);
-
-
- $cache_return = self::getsFromCache($ids);
- $non_cache_ids = array_diff($ids, array_keys($cache_return));
- if (!$non_cache_ids) {
- return $cache_return;
- }
-
-
- $db_return = self::getsFromDB($non_cache_ids);
- if ($db_return) {
- self::setToCache($db_return);
- }
- foreach ($ids as $id) {
- if (isset($cache_return[$id])) {
- $return[$id] = $cache_return[$id];
- continue;
- }
-
- if (isset($db_return[$id])) {
- $return[$id] = $db_return[$id];
- continue;
- }
- }
-
- return $return;
- }
-
-
- private function getsFromDB(array $ids) {
- $return = array();
- $condition = array(
- $this->primaryKey => $ids,
- );
- $result = $this->findBy($condition, $this->primaryKey);
- if (!$result) {
- return $return;
- }
- foreach ($ids as $id) {
- $id = (string) $id;
- if (array_key_exists($id, $result)) {
- $return[$id] = $result[$id];
- }
- }
- return $return;
- }
-
-
- public function getTableCacheFlag() {
- if ($this->tableCacheFlag) {
- return $this->tableCacheFlag;
- }
-
- $dbconfig = Config::getInstance()->get('db');
- $cacheKey_elements = array(
- serialize($dbconfig[$this->cluster_flag]),
- $this->tableName,
- 'table_cache_flag',
- );
- $key = Math::md5_16(join($cacheKey_elements, '::'));
- $objMemcached = new Memcached($this->memcacheClusterFlag);
- $tmpGetResult = $objMemcached->get($key);
- if ($tmpGetResult) {
- $this->tableCacheFlag = $tmpGetResult;
- return $this->tableCacheFlag;
- }
-
- if (is_null($tmpGetResult)) {
- $tmpVal = microtime(true);
- if ($objMemcached->set($key, $tmpVal, 0)) {
- $this->tableCacheFlag = $tmpVal;
- return $this->tableCacheFlag;
- }
-
-
- throw new DaoException(DaoException::CACHE_SET_TABLE_FLAG_ERROR);
- }
-
- if (!$tmpGetResult) {
-
- throw new DaoException(DaoException::CACHE_SERVICE_UNAVAILABLE);
- }
- }
-
-
- public function getsCacheKeys(array $ids) {
- $tableCacheFlag = $this->getTableCacheFlag();
- $cacheKeys = array();
- $dbconfig = Config::getInstance()->get('db');
- foreach ($ids as $id) {
- $cacheKey_elements = array(
- $tableCacheFlag,
- serialize($dbconfig[$this->cluster_flag]),
- $this->tableName,
- $id,
- 'row_cache',
- );
- $cacheKeys[$id] = Math::md5_16(join($cacheKey_elements, '::'));
- }
-
- return $cacheKeys;
- }
-
-
- private function getsFromCache(array $ids) {
- $return = array();
- if (!$this->useCache) {
- return $return;
- }
- try {
- $cacheKeys = self::getsCacheKeys($ids);
- } catch (DaoException $e) {
- return $return;
- }
-
- $objMemcached = new Memcached($this->memcacheClusterFlag);
- $cacheVals = $objMemcached->gets($cacheKeys);
-
- $cache_return = array_combine(array_keys($cacheKeys), $cacheVals);
- foreach ($cacheVals as $tmpK => $tmpV) {
- if (is_null($tmpV)) {
- continue;
- }
-
- $return[array_search($tmpK, $cacheKeys)] = $tmpV;
- }
-
- return $return;
- }
-
-
- private function deleteFromCache($id) {
- if (!$this->useCache) {
- return false;
- }
- $objMemcached = new Memcached($this->memcacheClusterFlag);
-
- if (Verify::unsignedInt($id)) {
- try {
- $cacheKeys = self::getsCacheKeys(array($id));
- } catch (DaoException $e) {
- return false;
- }
- return $objMemcached->delete(array_pop($cacheKeys));
- }
-
- if (is_array($id) && !empty($id)) {
- try {
- $cacheKeys = self::getsCacheKeys($id);
- } catch (DaoException $e) {
- return false;
- }
-
- if (count($cacheKeys) == 1) {
- return $objMemcached->delete(array_pop($cacheKeys));
- }
- return $objMemcached->deletes($cacheKeys);
- }
-
- return false;
- }
-
-
- public function deleteAllCaches() {
- if (!$this->useCache) {
- return false;
- }
-
- try {
- $tableCacheFlag = $this->getTableCacheFlag();
- } catch (DaoException $e) {
- return false;
- }
-
- $objMemcached = new Memcached($this->memcacheClusterFlag);
- return $objMemcached->delete($tableCacheFlag);
- }
-
-
- private function setToCache(array $results) {
- if (!$this->useCache) {
- return false;
- }
- if (!$results) {
- return false;
- }
- try {
- $cacheKeys = self::getsCacheKeys(array_keys($results));
- } catch (DaoException $e) {
- return false;
- }
- $objMemcached = new Memcached($this->memcacheClusterFlag);
- return $objMemcached->sets(array_combine($cacheKeys, $results), $this->cache_expiration);
- }
-
- private function _create(array $tableInfo, $isAutoIncrement = true, $action = self::PARAM_CREATE_ACTION_INSERT) {
- if(empty($tableInfo)) return false;
- switch($action) {
- case self::PARAM_CREATE_ACTION_INSERT :
- case self::PARAM_CREATE_ACTION_INSERT_IGNORE :
- case self::PARAM_CREATE_ACTION_REPLACE :
- break;
- default:
- throw new Exception('error insert action');
- }
- $sql = "{$action} {$this->tableName}
- SET
- ";
- $sqlSets = '';
- $tableInfo = $this->quote($tableInfo);
- foreach($tableInfo as $key => $val) {
- if($sqlSets != '') $sqlSets .= ' ,';
- $sqlSets .= "
- `{$key}` = {$val}
- ";
- }
- $sql .= $sqlSets;
- if($this->db->query($sql)) {
- if($isAutoIncrement) {
- $id = $this->db->insertId();
-
-
- self::deleteFromCache($id);
-
- return $id > 0 ? $id : true;
- } else {
- return true;
- }
- }
- return false;
- }
-
- public function replace(array $tableInfo, $isAutoIncrement = true) {
- return $this->_create($tableInfo, $isAutoIncrement, self::PARAM_CREATE_ACTION_REPLACE);
- }
-
- public function create(array $tableInfo, $isAutoIncrement = true) {
- return $this->_create($tableInfo, $isAutoIncrement, self::PARAM_CREATE_ACTION_INSERT);
- }
-
- public function insertIgnore(array $tableInfo, $isAutoIncrement = true) {
- return $this->_create($tableInfo, $isAutoIncrement, self::PARAM_CREATE_ACTION_INSERT_IGNORE);
- }
-
- public function insertDuplicate(array $tableInfo, array $onDuplicate = array()) {
- if (!$tableInfo) {
- return false;
- }
- $tmpArrKeys = array();
- foreach ($tableInfo as $tmpKey => $tmpV) {
- $tmpArrKeys[] = "`{$tmpKey}`";
- }
- $sql = "INSERT INTO {$this->tableName} (" . join(', ', $tmpArrKeys). ") VALUES ";
- $tmpArrValues = array();
- $new_tableInfo = $this->quote($tableInfo);
- foreach ($new_tableInfo as $tmpKey => $tmpV) {
- $tmpArrValues[] = $tmpV;
- }
- $sql .= " ( " . join(', ', $tmpArrValues) . " ) ";
- $sql .= "
- ON DUPLICATE KEY UPDATE
- ";
- $tmpArrDps = array();
- if (empty($onDuplicate)) {
- $onDuplicate = $tableInfo;
- }
- $new_onDuplicate = $this->quote($onDuplicate);
- foreach ($new_onDuplicate as $tmpKey => $tmpV) {
- $tmpArrDps[] = " `{$tmpKey}` = {$tmpV} ";
- }
- $sql .= join(', ', $tmpArrDps);
- if (!$this->db->query($sql)) {
- return false;
- }
- $id = $this->db->insertId();
-
-
- self::deleteFromCache($id);
-
- return $id > 0 ? $id : true;
- }
-
- public function update(array $tableInfo, array $condition) {
- if(empty($tableInfo)) return false;
- $sql = "UPDATE {$this->tableName}
- SET
- ";
- $sqlSets = '';
- foreach($tableInfo as $key => $val) {
- if($sqlSets != '') $sqlSets .= ' ,';
- $sqlSets .= "
- `{$key}` = {$this->quote($val)}
- ";
- }
- $sql .= $sqlSets;
- $where = $this->parseCondition($condition);
- $sql .= "
- {$where}
- ;
- ";
- $tmpQueryResult = $this->db->query($sql);
-
- if ($tmpQueryResult) {
- if (isset($condition[$this->primaryKey])) {
-
- self::deleteFromCache($condition[$this->primaryKey]);
- } else {
- $this->deleteAllCaches();
- }
- }
-
- return $tmpQueryResult;
- }
-
- public function delete($condition) {
- $where = $this->parseCondition($condition);
- $sql = "DELETE FROM {$this->tableName}
- {$where}
- ;
- ";
-
- $tmpQueryResult = $this->db->query($sql);
-
- if ($tmpQueryResult) {
- if (isset($condition[$this->primaryKey])) {
-
- self::deleteFromCache($condition[$this->primaryKey]);
- } else {
- $this->deleteAllCaches();
- }
- }
-
- return $tmpQueryResult;
- }
-
- public function quote($data) {
- return SqlHelper::escape($data, true);
- }
-
- static protected function isValidPK($pk) {
- return SqlHelper::isValidPK($pk);
- }
-
- static protected function isValidPKWithArray(array $arr, $key) {
- return SqlHelper::isValidPKWithArray($arr, $key);
- }
-
- public function totals($condtion = null){
- $result = $this->findBy($condtion, null, null, "count(*)");
- if (!$result) {
- return 0;
- }
- return (int) array_pop(array_pop($result));
- }
- }
|