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

18.06K
.
ramzes
поправка (+/-)

/**
 * Class SqlBuilder
 * @package microapp
 */
class SqlBuilder {

    /**
     * @var array
     */
    private $query = array();
    private $compilate = '';

    public function __construct(){
        return $this;
    }

    public function select($query){
        $this->query['select'] = is_array($query) ? implode(', ', array_map(array(get_class($this), 'article'), $query)) : $this->article($query);
        return $this;
    }

    public function insert($query){
        $this->query['insert'] = false;
        return $this;
    }

    public function update(){
        $this->query['update'] = false;
        return $this;
    }

    public function delete(){
        $this->query['delete'] = false;
        return $this;
    }

    public function from($table){
        $this->query['from'] = $this->article($table);
        return $this;
    }

    public function left($table){
        $this->query['left'] = $this->article($table);
        return $this;
    }

    public function right($table){
        $this->query['right'] = $this->article($table);
        return $this;
    }

    public function on($query){
        $this->query['on'] = $query;
        return $this;
    }

    public function where($where){
        if(preg_match('#([^=<>\!]+)#', $where, $row)){
            $this->query['where'] = str_replace($row[1], $this->article($row[1]), $where);
        }else{
            $this->query['where'] = $where;
        }
        return $this;
    }

    public function order($field, $type = 'ASC'){
        $this->query['order'][] = $this->article($field).' '.(strtoupper($type)=='ASC' ? 'ASC' : 'DESC');
        return $this;
    }

    public function limit($start, $len = false){
        $this->query['limit'] = $start;
        if($len!=false){
            $this->query['limit_len'] = $len;
        }
        return $this;
    }

    public function set(array $value){
        $this->query['set'] = $value;
        return $this;
    }



    public function run(){
        foreach ($this->query as $q => $v) {
            switch ($q) {
                case 'limit':
                    $this->compilate.= ' LIMIT';
                    break;
                case 'limit_len':
                    $this->compilate.= ' ,';
                    break;
                case 'order':
                    $this->compilate.= ' ORDER BY';
                    break;
                case 'sort':
                    $this->compilate.= '';
                    break;
                case 'right':
                    $this->compilate.= ' RIGHT JOIN';
                    break;
                case 'left':
                    $this->compilate.= ' LEFT JOIN';
                    break;
                case 'insert':
                    $this->compilate.= ' INSERT INTO';
                    break;
                default:
                    $this->compilate.= ' '.strtoupper($q);
                    break;
            }

            if($q=='on') {
                $split = explode('=', $v);
                $this->compilate .= ' ' . $this->query['from'] . '.' . $this->article($split[0]) . ' = ' . (isset($this->query['left']) ? $this->query['left'] : $this->query['right']) . '.' . $this->article($split[1]) . ' ';
            }else if($q=='order'){
                $this->compilate .= implode(', ', $v);
            }else if (is_array($v)) {
                $this->compilate .= ' ' . implode(', ', $v);
            }else{
                $this->compilate.= ($v != false) ? ' ' . $v . ' ' : '';
            }
        }
    }

    public function exec(){
        $this->run();
        return microapp::sql()->query($this->compilate);
    }

    public function view(){
        $this->run();
        return $this->compilate;
    }

    private function article($row){
        return preg_replace('|([a-z\d_\-]+)|is', '`\1`', str_replace('`', '', trim($row) ) );
    }

}

SELECT `forum_thread`.*, `users`.`login`, `users`.`ontime`, `users`.`name` 
FROM `forum_thread`  LEFT JOIN `users` 
ON `forum_thread`.`last_post_author` = `users`.`id` 
WHERE `forum_thread`.`parent_id`= 4 
ORDER BY`forum_thread`.`thread_fixed` DESC, `forum_thread`.`last_time` DESC
LIMIT 20
.
(\/)____o_O____(\/)

ramzes, и не ругается что конструктор содержит ретурн?

.
# Koenig (07.04.2015 / 07:30)
ramzes, и не ругается что конструктор содержит ретурн?
нет. а с чего он должен ругаться?
.
public function __construct (){
    return $this ;
}


Гг, а без этого он объект не возвращает?
.
# L!MP (07.04.2015 / 12:43)
public function __construct (){
    return $this ;
}


Гг, а без этого он объект не возвращает?
можно и без этого
.
reaper

ramzes, Конструктор не должен ничего возвращать. Независимо от того, есть там return или нет, всегда будет получен экземпляр класса. Здесь тебе не питон. С метапрограммированием здесь хреновато.

<?php

class A
{
    public function __construct() 
    {
        return 1;
    }
}

$a = new A(); 

var_dump($a);
// object(A)#1 (0) {}

var_dump(get_class($a));
// string(1) "A"

var_dump(gettype($a));
// string(6) "object"

var_dump($a->hello());
// string(5) "Hello"
.
(\/)____o_O____(\/)

ramzes, кстати array_map(array(get_class($this), 'article') get_class лишний, хватит $this

.
(\/)____o_O____(\/)

тоже продолжил свой быдлокод, пока коряво, не кошерно, покажу наброски

.
# Koenig (07.04.2015 / 23:41)
ramzes, кстати array_map(array(get_class($this), 'article') get_class лишний, хватит $this
не заводится у меня без гет класс
.
(\/)____o_O____(\/)

мыслей много, но требуются додумки

class KMysqli extends Mysqli {
    use KsqlUtils, KsqlArgs, KsqlQueries;
    
    //
    # пересмотреть старый класс
    //
    
    public function sqlBuild() {
        // тут сам конструктор из массивов
    }
}

замутки (+/-)

trait KsqlQueries {
    
    private $pre = false;
    private $post = false;
    
    public function select($fieldsListArray = '*') {
        $this->pre = 'SELECT ' . (is_array($fieldsListArray) ? $this->concat(array_values($fieldsListArray)) : $fieldsListArray);
        $this->post = ' FROM ';
        
        return $this;
    }
    
    public function count($field = '*') {
        $this->pre = 'SELECT COUNT(' . $this->art($field) . ')';
        $this->post = ' FROM ';
        
        return $this;
    }
    
    public function delete() {
        $this->pre = 'DELETE';
        $this->post = ' FROM ';
        
        return $this;
    }
    
    public function insert() {
        $this->pre = 'INSERT INTO';
        $this->post = ' ';
        
        return $this;
    }
    
    public function update() {
        $this->pre = 'UPDATE';
        $this->post = ' ';
        
        return $this;
    }
}

trait KsqlArgs {
    
    private $table = array();
    private $on = array();
    private $limit;
    private $offset;
    private $where = array();
    private $order = array();
    private $group = array();
    
    public function table($table) {
        $this->table[] = $table;
        
        return $this;
    }
    
    public function on($field1, $field2) {
        $this->on[] = $field1 . ' = ' . $field2;
        
        return $this;
    }
    
    public function where($field, $type, $value) {
        $this->where[] = $this->art($field) . ' ' . $type . ' ' . esc($value);
        
        return $this;
    }
    
    //
    # прочие Where
    //
    
    public function group($field) {
        $this->group[] = $this->art($field);
        
        return $this;
    }
    
    public function order($field, $type = 'asc') {
        $type = in_array($type, array('asc', 'desc')) ? $type : 'asc';
        $this->order[] = $this->art($field) . ' ' . strtoupper($type);
        
        return $this;
    }
    
    public function offset($offset = 0) {
        $this->offset = $offset;
        
        return $this;
    }
    
    public function limit($limit) {
        $this->limit = $limit;
    }
}

trait KsqlUtils {
    
    public function concat($array, $type = 'comma') {
        $types = array('comma' => ',', 1 => 'and');
        return $this->art(implode(' ' . $types[$type], array_values($array)));
    }
    
    public function art($string) {
        return '`' . str_replace('.', '`.`', str_replace('`', '', $string)) . '`';
    }
    
    public function esc($data) {
        if (!is_array($data)) {
            $data = is_int($data) ? $data : '"' . mysql_real_escape_string($data) . '"';
        } else {
            $data = array_map(array($this, 'esc'), $data);
        }

        return $data;
    }

}


ну и то что пока получается по вызову
$db_host = '127.0.0.1'; 
$db_user = 'root'; 
$db_pass = ''; 
$db_name = 'test'; 
$db_charset = 'utf-8'; 

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

$mysqli->select(array('users.name', 'users.id', 'forum_themes.name', 'forum_themes.id', 'forum_posts.text', 'forum_posts.time'))
    ->table('forum_posts')->table('forum_themes')->table('users')
    ->on('forum_posts.author', 'users.id')->on('forum_themes.id', 'forum_posts.tid')
    ->limit(1);
Всего: 362