
Эксперт
  
Профиль
Группа: Участник Клуба
Сообщений: 1724
Регистрация: 30.12.2002
Где: бункер
Репутация: нет Всего: 22
|
смешной пример, зато реальный: использование | Код | if(count($this->userinfo['roles'])) { $acls = $db->select('SELECT tp.name as permname, tp.perm_id,BIT_OR(tacl.mask) as resmask FROM `%s` tp LEFT JOIN `%s` tacl ON tacl.role_id IN (%s) AND tacl.perm_id=tp.perm_id GROUP BY tp.perm_id', $config->tables['perms'], $config->tables['auth/acl'], implode(',', $this->userinfo['roles']) ); /*cache acl $acls = $DB->select(sprintf('SELECT tr.name,ta.mask FROM `%s` tr LEFT JOIN %s ta ON ta.perm_id = tr.perm_id AND (ta.user_id = %d OR ta.group_id = %d)', $ts['perms'], $ts['acl'], $user_id, $this->userinfo['group_id']));*/ while($resource = $db->fetch($acls)) { $this->userinfo['access'][$resource['permname']] = $resource['resmask']; } }
|
класс db создается гдето так: | Код | $db = $GLOBALS['db'] = datasource::factory($ds);//factory inside
|
сами классы такие: | Код | <?php /********************************
2006 Vaulter <[email protected]> part of system :) db layer **********************************/ define('_DBDRIVERS',dirname(__FILE__).DIRECTORY_SEPARATOR.'drivers'.DIRECTORY_SEPARATOR);//some drivers at ex. define('_DBDRIVEREXT','php');//some drivers at ex. .class.driver define('_DBFETCH_ARRAY',1);//fetch as array define('_DBFETCH_ASSOC',2);//fetch as assoca array define('_DBFETCH_BOTH',4);//fetch as assoca array define('_DBFETCH_TREE',8);//fetch as tree...TODO
class datasource/*OLD DB class */ extends object { static public $dsns;//connected ready datasources;//array? function __construct($dsn = null)//factory { // if($dsn) $this->factory($dsn); } function connect($dsn = null/*default actions?*/) { } static function factory($dsn = null)/* if null what to do? */ { if(datasource::$dsns[$dsn]) return datasource::$dsns[$dsn]; //else init connect if($dsn) $parsed = datasource::parseDSN($dsn); else $parsed = array('hostspec' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'test', 'phptype' => 'mysqli', );//stupid defaults if($parsed['phptype'])//mysql ... { $driver = _DBDRIVERS.$parsed['phptype'].'.'._DBDRIVEREXT; if(file_exists($driver)) { include $driver; $classname = $parsed['phptype'].'_Layer'; datasource::$dsns[$dsn] = new $classname($parsed); datasource::$dsns[$dsn]->connect($parsed);//needed there? or in constructor of driver? return datasource::$dsns[$dsn]; } else datasource::setError('datasource/notfound',$driver);//'cannot load driver: '.$driver); } } /** * Parse a data source name. * * @param string $dsn Data Source Name to be parsed * * @return array an associative array with the following keys: * + phptype: Database backend used in PHP (mysql, odbc etc.) * + dbsyntax: Database used with regards to SQL syntax etc. * + protocol: Communication protocol to use (tcp, unix etc.) * + hostspec: Host specification (hostname[:port]) * + database: Database to use on the DBMS server * + username: User name for login * + password: Password for login * * @author Tomas V.V.Cox <[email protected]> */ static function parseDSN($dsn) { $parsed = array( 'phptype' => false, 'dbsyntax' => false, 'username' => false, 'password' => false, 'protocol' => false, 'hostspec' => false, 'port' => false, 'socket' => false, 'database' => false, );
if (is_array($dsn)) { $dsn = array_merge($parsed, $dsn); if (!$dsn['dbsyntax']) { $dsn['dbsyntax'] = $dsn['phptype']; } return $dsn; }
// Find phptype and dbsyntax if (($pos = strpos($dsn, '://')) !== false) { $str = substr($dsn, 0, $pos); $dsn = substr($dsn, $pos + 3); } else { $str = $dsn; $dsn = null; }
// Get phptype and dbsyntax // $str => phptype(dbsyntax) $arr = null; if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { $parsed['phptype'] = $arr[1]; $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; } else { $parsed['phptype'] = $str; $parsed['dbsyntax'] = $str; }
if (!count($dsn)) { return $parsed; }
// Get (if found): username and password // $dsn => username:password@protocol+hostspec/database if (($at = strrpos($dsn,'@')) !== false) { $str = substr($dsn, 0, $at); $dsn = substr($dsn, $at + 1); if (($pos = strpos($str, ':')) !== false) { $parsed['username'] = rawurldecode(substr($str, 0, $pos)); $parsed['password'] = rawurldecode(substr($str, $pos + 1)); } else { $parsed['username'] = rawurldecode($str); } }
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database $match = null; if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { $proto = $match[1]; $proto_opts = $match[2] ? $match[2] : false; $dsn = $match[3];
// $dsn => protocol+hostspec/database (old format) } else { if (strpos($dsn, '+') !== false) { list($proto, $dsn) = explode('+', $dsn, 2); } if (strpos($dsn, '/') !== false) { list($proto_opts, $dsn) = explode('/', $dsn, 2); } else { $proto_opts = $dsn; $dsn = null; } }
// process the different protocol options $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; $proto_opts = rawurldecode($proto_opts); if ($parsed['protocol'] == 'tcp') { if (strpos($proto_opts, ':') !== false) { list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); } else { $parsed['hostspec'] = $proto_opts; } } elseif ($parsed['protocol'] == 'unix') { $parsed['socket'] = $proto_opts; }
// Get dabase if any // $dsn => database if ($dsn) { // /database if (($pos = strpos($dsn, '?')) === false) { $parsed['database'] = $dsn; // /database?param1=value1¶m2=value2 } else { $parsed['database'] = substr($dsn, 0, $pos); $dsn = substr($dsn, $pos + 1); if (strpos($dsn, '&') !== false) { $opts = explode('&', $dsn); } else { // database?param1=value1 $opts = array($dsn); } foreach ($opts as $opt) { list($key, $value) = explode('=', $opt); if (!isset($parsed[$key])) { // don't allow params overwrite $parsed[$key] = rawurldecode($value); } } } }
return $parsed; } } abstract class dblayer extends object { private $link; private $version;//hm some collations stuff switching by config function __construct($dsn = null) {//connect! //echo 'dblayer construct<br />'; if(!empty($dsn))$this->link = $this->connect($dsn); } abstract function lastInsertID($table = null, $field = null); // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051 //return $this->selectCell('SELECT LAST_INSERT_ID()');//SQL92??? abstract function connect($dsn = null); function __destruct() { /* if(!empty($this->link)) { mysql_close($this->link); //sys_log('mysql closed'); }*/ } function tableExists($tablename) { $res = $this->query("SHOW TABLES LIKE '$tablename'");//SQL92? if($this->_count($res) > 0) return true; else return false; } function createTable($tablename,$spec = null,$force=false) { //do query $query = "create table ".($force?"":" IF NOT EXISTS ")." `$tablename` $spec"; return $this->query($query); } abstract function escape($data); /* return mysql_real_escape_string($data); */ /*возвращает колонку, need argc */ function selectCell($query) {//do query if(func_num_args() > 1) { $args = func_get_args(); array_shift($args);//query $sql = vsprintf($query,$args); $query = & $sql;//alias } $res = $this->query($query); if($res && $this->numRows($res)) { $arr = $this->fetch($res); if(isset($cell)) return $arr[$cell]; return $arr[0]; } } function selectRow($query)//???? queryRow fetchmode set via function TODO { if(func_num_args() > 1) { $args = func_get_args(); array_shift($args);//query $sql = vsprintf($query,$args); $query = & $sql;//alias } $res = $this->query($query); if($res && $this->numRows($res)) { $arr = $this->fetch($res);// return $arr; } return null; } function select($query) { if(func_num_args() > 1) { $args = func_get_args(); array_shift($args);//query $sql = vsprintf($query,$args); $query = & $sql;//alias } return $this->query($query); } function insert($table,$fields = array()) { $keys = array_keys($fields);// check if we have numeric if(is_numeric($keys[0]))//we have numeric array - remove all non numeric fields! { foreach($fields as $key=>$value) if(is_numeric($key)) $newfields[$key] = $value;
$fields = $newfields; } else {//do assoc query $f = "`".implode("`,`",$keys)."`";
} $values = "'".implode("','",$fields)."'";//we be 'value1','value2' if(!empty($f)) $query = "INSERT INTO `$table` ($f) VALUES ($values)"; else $query = "INSERT INTO `$table` VALUES ($values)";
$ok = $this->_query($query); if(!$ok) return false; return mysql_insert_id($this->link); } function query($query) { if(defined('_SQLDEBUG') || @$_GET['debug']=='vkl' )slog($query,'debugsql');//TOO SLOOOW!!! //continue to layer } abstract function numRows($res = null); //if(is_resource($res))return mysql_num_rows($res); //elseif($aff = mysql_affected_rows($this->link)) return $aff; //else return null; abstract function fetch($res, $mode = _DBFETCH_BOTH); //if null get last result //return mysql_fetch_array($res); abstract function free($res); //mysql_free_result($res);
} ?> |
|