Класс обертки Mysqli by Koenig (Допилить)

7.62K
.
(\/)____o_O____(\/)
Вобщем класс, пока не знаю что еще нужно, выкладываю на суд
Testing PHP Version 5.4.17
Заодно попробовал более менее выровнять код, и прокоментировать PHPDoc
/**
* KoeNysqli
* 
* Обертка для Mysqli
* 
* @author Koenig <http://johncms.com/users/profile.php?user=6565>
* @version 1.0
*/

class KoeMysql extends Mysqli
{
   /**
   * limit
   * 
   * @var integer or array 
   */    
  private $limit = false;
   /**
   * условия
   * 
   * @var array
   */
  private $where = false;
   /**
   * условия сортировки
   * 
   * @var array 
   */
  private $sort = false;
   /**
   * конструктор
   * 
   * @param string $db_host
   * @param string $db_user
   * @param string $db_pass
   * @param string $db_name
   * @param string $db_charset
   * @param integer $port
   * @return resource
   */
  public function __construct($db_host, $db_user, $db_pass, $db_name, $db_charset, $port = 3306)
  {
    @parent::__construct($db_host, $db_user, $db_pass, $db_name, $port);
    @$this->set_charset($db_charset);
    if ($this->connect_errno) die($this->connect_error);
  }
  /**
  * stmt count params => ?
  * 
  * @return integer
  */
  public function count_params()
  {
    return $this->stmt ? $this->stmt->param_count : die('stmt not started');
  }
  /**
  * stmt count fields in result
  * 
  * @param void
  * @return integer
  */
  public function count_fields()
  {
    return $this->stmt ? $this->stmt->field_count : die('stmt not started');
  }
  /**
  * return yes/no fetch result
  * 
  * @param void
  * @return boolean
  */
  public function is_fetch()
  {
    if ($this->stmt) {
      return preg_match('/select/i', $this->sql) ? true : false;
    }
    else {
      die('Query not execute');
    }
  }
  /**
  * sql query
  * 
  * @param string $sql
  * @param array $placeholders
  * @return result array|integer|string error
  */
  public function sql($sql, $placeholders = null)
  {
    $this->sql = $sql . $this->get_where() . $this->get_sort() . $this->get_limit();
    if (!$this->stmt = $this->prepare($this->sql)) {
      die('error sql <<< ' . $this->sql . ' >>>');
    }
    if ($this->count_params() && $placeholders) {
      if (!$this->set_placeholders($placeholders)) {
        die('Placeholders failed');
      }
    }
    if (!$this->is_fetch()) {
      $this->stmt->execute();
      return $this->stmt->affected_rows;
    }
    else {
      $this->stmt->execute();
      if (!$this->bind_result()) {
        die('Bind result failed');
      }
    }
    $this->limit = false;
    $this->sort = false;
    $this->where = false;
    return $this->fetch_result();
  }
  /**
  * autofetch
  * 
  * @param void
  * @return array|integer|boolean
  */
  public function fetch_result()
  {
    if (!$this->stmt->num_rows) {
      $return = false;
    }
    if ($this->count_fields() == 1) {
      $res = $this->stmt->get_result();
      $row = $res->fetch_row();
      $return = $row[0];
    }
    else {
      $return = array();
      $res = $this->stmt->get_result();
      while ($row = $res->fetch_assoc()) {
        array_push($return, $row);
      }
    }
    return $return;
  }
  /**
  * bind result for placeholders
  * @param void
  * @return mysqli_stmt
  */
  public function bind_result()
  {
    $result = array();
    $binds = array();
    $meta = $this->stmt->result_metadata();
    while ($field = $meta->fetch_field()) {
      $binds[] = & $row[$field->name];
    }
    if (!call_user_func_array(array(
      $this->stmt,
      'bind_result'
    ) , $binds)) {
      die('Not bind result');
    }
    return $this->stmt;
  }
  /**
  * set placeholders
  * 
  * @param array $args
  * @return mysqli_stmt
  */
  public function set_placeholders($args)
  {
    if (!is_array($args)) {
      $args = array(
        $args
      );
    }
    $types = '';
    $newarray = array();
    for ($i = 0; $i < sizeof($args); $i++) {
      $types.= is_numeric($args[$i]) ? 'i' : ((is_double($args[$i]) || is_float($args[$i])) ? 'd' : 's');
      $newarray[] = $args[$i];
    }
    $args = array();
    $args[] = $types;
    foreach($newarray as $k => $v) {
      $args[] = & $newarray[$k];
    }
    if (!call_user_func_array(array(
      $this->stmt,
      'bind_param'
    ) , $args)) {
      die('Not bind params');
    }
    return $this->stmt;
  }
  /**
  * set where params
  * 
  * @param array $args
  * @return string @where
  */
  public function set_where($args)
  {
    if (is_array($args)) {
      $newarray = array();
      if (sizeof($args) > 0) {
        foreach($args as $k => $v) {
          $newarray[] = '`' . $k . '` = ' . (($v != '?') ? '"' . $v . '"' : $v);
        }
        return $this->where = ' WHERE ' . implode(' AND ', $newarray);
      }
      else {
        return $this->where = ' WHERE 1';
      }
    }
  }
  /**
  * set limits
  * 
  * @param array or integer $args
  * @return string @limit 
  */
  public function set_limit($args)
  {
    if (is_array($args) && sizeof($args) == 2) {
      $str = ' LIMIT ' . implode(' ,', array_values($args));
    }
    elseif (is_int($args)) {
      $str = ' LIMIT ' . $args;
    }
    else {
      die('Number of arguments 1 (string) or 2 (array)');
    }
    return $this->limit = $str;
  }
  /**
  * set sort params
  * 
  * @param array $args
  * @return string @sort 
  */
  public function set_sort($args)
  {
    if (is_array($args) && sizeof($args) > 0) {
      $str = ' order by ';
      $x = 1;
      $i = sizeof($args);
      foreach($args as $k => $v) {
        $typesort = $v == 'a' ? 'asc' : 'desc';
        $str.= $k . ' ' . $typesort;
        if ($x != $i) {
          $str.= ', ';
        }
        else {
          $str.= ' ';
        }
        $x++;
      }
    }
    return $this->sort = $str;
  }
  /**
  * get sort
  * 
  * @param void
  * @return string @sort
  */
  public function get_sort()
  {
    return $this->sort;
  }
  /**
  * get limit
  * 
  * @param void
  * @return string @limit
  */  
  public function get_limit()
  {
    return $this->limit;
  }
  /**
  * get where
  * 
  * @param void
  * @return string @where
  */  
  public function get_where()
  {
    return $this->where;
  }
}
Прикрепленные файлы:
.
(\/)____o_O____(\/)
Testing
/* 
-- 
-- Table structure for table `table` 
-- 

CREATE TABLE IF NOT EXISTS `table` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `name` text NOT NULL, 
  `pass` varchar(32) NOT NULL, 
  `time` int(11) NOT NULL, 
  `pid` int(11) NOT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 
*/ 

$db_host = '127.0.0.1'; 
$db_user = 'root'; 
$db_pass = ''; 
$db_name = 'test'; 
$db_charset = 'utf-8'; 

$mysqli = new KoeMysql($db_host, $db_user, $db_pass, $db_name, $db_charset);

$sql = "insert into `table` (`name`, `pass`, `time`, `pid`) values (?, ?, ?, ?)";  
$array = array('test', 'qwerty', time(), 213); 
$res = $mysqli->sql($sql, $array);
echo '<pre>'; print_r($res);   

$sql = "select * from `table`"; 
$mysqli->set_where(array('pid' => '?', 'name' => '?')); 
$mysqli->set_limit(array(2, 2));
#$mysqli->set_limit(5);
$mysqli->set_sort(array('id' => 'd', 'time' => 'a'));
$placeholders = array(213, 'test');
$res = $mysqli->sql($sql, $placeholders); 
echo '<pre>'; print_r($res);   

$sql = "delete from `table` where `id` < ?";  
$placeholders = 100;
$res = $mysqli->sql($sql, $placeholders); 
echo '<pre>'; print_r($res); 

$sql = 'select count(id) from `table`';
$res = $mysqli->sql($sql);
echo '<pre>'; print_r($res);
.
phpdoc на русском???
.
(\/)____o_O____(\/)
No-Tactic, местами
.
(\/)____o_O____(\/)
кто посоветует как организовать в условиях > < <= >= !=
.
(\/)____o_O____(\/)
есть мысль, сейчас попробую сделать
.
Koenig, похвально, но велик ИМХО. неужели на пхп нет орм, раз ты пишиш велик?
и еще, почему описание функции до ее обьевления, а не в теле функции? или на пхп так принято?
.
(\/)____o_O____(\/)
flaky, так принято наверное, я недавно начал коментировать, вроде работает
Прикрепленные файлы:
.
(\/)____o_O____(\/)
flaky, ОРМ это не много не то, тут работа с бд, ОРМ - это уже база в виде объектов
.
pyramid_head, а то что строки документирования это не коментарий а строка вас наверно тоже удивило
Koenig ну это же похоже на запросы орм, только без обьектов таблиц.
Всего: 362