400行代码实现php.mvc框架

400行代码实现简单的mvc框架,框架代码包含在入口文件中没有其他的加载,提供了mvc框架的基本功能,使用简单可以通过加载其他类库进行扩展。代码中已提供简单的例子。

classs文件夹:保存其他类库,通过load_class(name)函数加载。 config文件夹:保存配置文件config.php(保存设置参数数组)。 controllers文件夹;保存控制器文件(访问/index/login=>执行index_controller类中的login_action方法)。 models文件夹;保存模型文件,通过model(name)函数加载。
others文件夹:保存程序其他文件。
public文件夹:保存静态文件(css、js、img)。
views文件夹:保存视图文件。

1 . [图片] xxx.jpg

这里写图片描述

2 . 入口文件index.php

<?php
$endrun=false;
define("IN_APP",true);
//定义目录
define("CONTROLLERS_DIR",dirname(__FILE__).DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR);
define("VIEWS_DIR",dirname(__FILE__).DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR);
define("MODELS_DIR",dirname(__FILE__).DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR);
define("CONFIG_DIR",dirname(__FILE__).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR);
define("CLASSS_DIR",dirname(__FILE__).DIRECTORY_SEPARATOR.'classs'.DIRECTORY_SEPARATOR);
define("CONFIG_FILE",'config.php');
//加载配置文件
if(file_exists(CONFIG_DIR.CONFIG_FILE))
{
    require_once(CONFIG_DIR.CONFIG_FILE);
}
//初始化
function inti()
{
    register_shutdown_function('shutdown_func');
    if(version_compare(PHP_VERSION,'5.4.0','<')) 
    {
        ini_set('magic_quotes_runtime',0);
    }
    if(get_config('session')=='on')
    {
        session_start();
    }
    if(get_config('charset')!=null)
    {
        ini_set('default_charset',get_config('charset'));
    }
    if(get_config('appname')!=null)
    {
        header('X-Powered-By:'.get_config('appname'));
    }
    if(get_config('timezone')!=null)
    {
        ini_set('date.timezone',get_config('timezone'));
    }
    if(get_config('debug')!=null)
    {
        if(get_config('debug')==false)
        {
            ini_set("display_errors", "off");
        }
        if(get_config('debug')==true)
        {
            ini_set("display_errors", "on");
        }
    }
}
//获取配置
function get_config($key)
{
    if(isset($GLOBALS['config']))
    {
        if(is_array($GLOBALS['config']))
        {
            if(array_key_exists($key,$GLOBALS['config']))
            {
                return $GLOBALS['config'][$key];
            }
        }
    }
    return null;
}
//判断请求方法
function is_method($method)
{
    $m=$_SERVER['REQUEST_METHOD'];
    if(strtoupper($method)==$m)
    {
        return true;
    }
    return false;
}
//判断是否是ajax请求
function is_ajax()
{
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        return true;
    }
    else
    {
        return false;
    }
}
//设置、获取session
function session($name,$value=null)
{
    if($value!=null)
    {
        $_SESSION[$name]=$value;
        return;
    }
    else
    {
        if(isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
        else
        {
            return false;
        }
    }
}
//删除session
function unsession($name)
{
    if(isset($_SESSION[$name]))
    {
        unset($_SESSION[$name]);
    }
}
//设置、获取cookie
function cookie($name,$value=null,$expire=null,$path=null,$domain=null)
{
    if($value!=null)
    {
        setcookie($name,$value);
        if($expire!=null)
        {
            setcookie($name,$value,time()+$expire);
            if($path!=null)
            {
                setcookie($name,$value,time()+$expire,$path);
                if($domain!=null)
                {
                    setcookie($name,$value,time()+$expire,$path,$domain);
                }
            }
        }
        return;
    }
    else
    {
        if(isset($_COOKIE[$name]))
        {
            return $_COOKIE[$name];
        }
        else
        {
            return false;
        }
    }
}
//删除cookie
function uncookie($name)
{
    if(isset($_COOKIE[$name]))
    {
        setcookie($name, "", time()-3600);
    }
}
//发送http请求
//$params="{user:\"admin\",pwd:\"admin\"}";  
//$headers=array('Content-type: text/json',"id: $ID","key:$Key");  
function http_request($URL,$type,$params,$headers){  
    $ch=curl_init();  
    $timeout=5;  
    curl_setopt ($ch,CURLOPT_URL,$URL); 
    if($headers!="")
    {  
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);  
    }
    else
    {  
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:application/json'));  
    }  
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);  
    switch($type)
    {  
        case "GET": 
            curl_setopt($ch,CURLOPT_HTTPGET,true);
            break;  
        case "POST": 
            curl_setopt($ch,CURLOPT_POST,true);   
            curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
            break;  
        case "PUT": 
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");   
            curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
            break;  
        case "DELETE":
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST, "DELETE");   
            curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
            break;  
    }  
    $file_contents=curl_exec($ch);
    return $file_contents;  
    curl_close($ch);  
}
//获取post变量  
function post($name,$type='str')
{
    if(isset($_POST[$name]))
    {
        if($type=='str')
        {
            return $_POST[$name];
        }
        if($type=="int")
        {
            if($_POST[$name]===intval($_POST[$name]).'')
            {
                return intval($_POST[$name]);
            }
        }
    }
    return false;
}
//获取get变量
function get($name,$type='str')
{
    if(isset($_GET[$name]))
    {
        if($type=='str')
        {
            return $_GET[$name];
        }
        if($type=="int")
        {
            if($_GET[$name]===intval($_GET[$name]).'')
            {
                return intval($_GET[$name]);
            }
        }
    }
    return false;
}
//页面跳转
function redirect($url)
{
    header('Location:'.$url);
    return;
}
//载入model
function model($name)
{
    $name.='_model';
    if(file_exists(MODELS_DIR.$name.'.php'))
    {
        require_once(MODELS_DIR.$name.'.php');
        if(class_exists($name))
        {
            $c=new $name;
            return $c;
        }
    }
    return false;
}
//载入class
function load_class($name)
{
    if(file_exists(CLASSS_DIR.$name.'.php'))
    {
        require_once(CLASSS_DIR.$name.'.php');
    }
}
//代码结束时执行
function shutdown_func()
{
    if(!$GLOBALS['endrun'])
    {
        status(500);
    }
}
//匹配路由
function map()
{
    $request_url=$_SERVER['REQUEST_URI'];
    if($request_url=='/')
    {
        instance('index','index');
    }
    else
    {
        $a=explode('/',$request_url);
        $length=count($a);
        $c=$a[1];
        if($length>=3)
        {
            $m=$a[2];
            if($m=="")
            {
                instance($c,$c);
            }
            else
            {
                instance($c,$m);
            }
        }
        else
        {
            instance($c,$c);
        }
    }
    $GLOBALS['endrun']=true;
}
//执行请求对应方法
function instance($c,$m)
{
    $c.='_controller';
    $m.='_action';
    if(file_exists(CONTROLLERS_DIR.$c.'.php'))
    {
        require_once(CONTROLLERS_DIR.$c.'.php');
        if(class_exists($c))
        {
            if(method_exists($c,$m))
            {
                $r=new $c;
                $r->$m();
            }
            else
            {
                status(404);
            }
        }
        else
        {
            status(404);
        }
    }
    else
    {
        status(404);
    }
}
//返回错误
function status($code)
{
    if($code==404)
    {
        header('HTTP/1.1 404 Not Found');
        text('404 错误!');
        return;
    }
    if($code==500)
    {
        header('HTTP/1.1 500 Internal Server Error');
        text('500 错误!');
        return;
    }
}
//输出json
function json($arr)
{
    header('content-type:application/json; charset=utf-8');
    if(is_array($arr))
    {
        echo json_encode($arr);
        return;
    }
    echo json_decode(array('code'=>0,'message'=>'parameter error'));
}
//返回json信息
function message($code,$str,$data=null)
{
    $a=array("code"=>$code,"message"=>$str,"data"=>$data);
    json($a);
}
//输出text
function text($str)
{
    header('content-type:text/plain; charset=utf-8');
    echo $str;
}
//渲染视图
function render($view,$data = null)
{
    $path=VIEWS_DIR.$view.'.php';
    if(file_exists($path))
    {
        header('content-type:text/html; charset=utf-8');
        ob_start();
        if(is_array($data))
        {
            extract($data);
        }
        require $path;
        echo trim(ob_get_clean());
    }
    else
    {
        text('template not found');
    }
}
//运行
function run()
{
    inti();
    map();
}
run();
?>

3 . [代码]配置文件config.php

<?php
$config=array(
    'appname'=>'myapp',
    'debug'=>true,
    'timezone'=>'Asia/Shanghai',
    'session'=>'on',
    'server'=>'localhost',
    'username'=>'root',
    'password'=>'root',
);
?>

4 . [代码]控制器index_controller

<?php
class index_controller
{
    public function index_action()
    {
        if(!session("username"))
        {
            redirect("/index/login");
        }
        $article=model("article");
        $list=$article->get_list(session("username"));
        render("index",array("username"=>session("username"),"list"=>$list));
    }
    public function login_action()
    {
        render("login");
    }
    public function login_ajax_action()
    {
        if(is_ajax())
        {
            $username=post("username","str");
            $password=post("password","str");
            if($username=='test'&&$password=='test')
            {
                session("username",$username);
                message(1,"登录成功!");
            }
            else
            {
                message(0,"用户名或密码错误!");
            }
        }
    }
}
?>

5 . [代码]数据模型article_model.php

<?php
class article_model
{   
    function get_list($name)
    {
        $list=array('php代码1','php代码2','php代码3');
        return $list;
    }
}
?>

6 . [代码]视图文件login.php

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0"/>
<title>login</title>
<script type="text/javascript" src="/public/js/jquery-1.11.1.js"></script>
</head>
<body>
<input type="text" id="username">
<input type="text" id="password">
<button id="login">登录</button>
<script>
$(function() {
    $("#login").click(function(){
        var username=$("#username").val();
        var password=$("#password").val();
        if(username==""||password=="")
        {
            return;
        }
        $.ajax({
            type: "POST",
            url: "/index/login_ajax",
            data: {username:username,password:password},
            dataType: "json",
            success: function(data){
                if(data.code==1)
                {
                    window.location.href='/index';
                }
                else
                {
                    alert(data.message);
                    return;
                }
            },
            error:function()
            {
                alert("提交失败!");
            }
        });
    });
});
</script> 
</body>
</html>

7 . [代码]视图文件index.php

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0"/>
<title>index</title>
<script type="text/javascript" src="/public/js/jquery-1.11.1.js"></script>
</head>
<body>
<h1><?php echo $username; ?></h1>
<ul>
<?php foreach($list as $item): ?> 
<li><?php echo $item; ?></li> 
<?php endforeach; ?> 
</ul>
</body>
</html>

8 . [代码].htaccess文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

9 . [代码]推荐数据库操作类库medoo

<?php
/*!
 * Medoo database framework
 * http://medoo.in
 * Version 1.0
 *
 * Copyright 2015, Angel Lai
 * Released under the MIT license
 */
class medoo
{
    // General
    protected $database_type;

    protected $charset;

    protected $database_name;

    // For MySQL, MariaDB, MSSQL, Sybase, PostgreSQL, Oracle
    protected $server;

    protected $username;

    protected $password;

    // For SQLite
    protected $database_file;

    // For MySQL or MariaDB with unix_socket
    protected $socket;

    // Optional
    protected $port;

    protected $prefix;

    protected $option = array();

    // Variable
    protected $logs = array();

    protected $debug_mode = false;

    public function __construct($options = null)
    {
        try {
            $commands = array();
            $dsn = '';

            if (is_array($options))
            {
                foreach ($options as $option => $value)
                {
                    $this->$option = $value;
                }
            }
            else
            {
                return false;
            }

            if (
                isset($this->port) &&
                is_int($this->port * 1)
            )
            {
                $port = $this->port;
            }

            $type = strtolower($this->database_type);
            $is_port = isset($port);

            if (isset($options[ 'prefix' ]))
            {
                $this->prefix = $options[ 'prefix' ];
            }

            switch ($type)
            {
                case 'mariadb':
                    $type = 'mysql';

                case 'mysql':
                    if ($this->socket)
                    {
                        $dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
                    }
                    else
                    {
                        $dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
                    }

                    // Make MySQL using standard quoted identifier
                    $commands[] = 'SET SQL_MODE=ANSI_QUOTES';
                    break;

                case 'pgsql':
                    $dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
                    break;

                case 'sybase':
                    $dsn = 'dblib:host=' . $this->server . ($is_port ? ':' . $port : '') . ';dbname=' . $this->database_name;
                    break;

                case 'oracle':
                    $dbname = $this->server ?
                        '//' . $this->server . ($is_port ? ':' . $port : ':1521') . '/' . $this->database_name :
                        $this->database_name;

                    $dsn = 'oci:dbname=' . $dbname . ($this->charset ? ';charset=' . $this->charset : '');
                    break;

                case 'mssql':
                    $dsn = strstr(PHP_OS, 'WIN') ?
                        'sqlsrv:server=' . $this->server . ($is_port ? ',' . $port : '') . ';database=' . $this->database_name :
                        'dblib:host=' . $this->server . ($is_port ? ':' . $port : '') . ';dbname=' . $this->database_name;

                    // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting
                    $commands[] = 'SET QUOTED_IDENTIFIER ON';
                    break;

                case 'sqlite':
                    $dsn = $type . ':' . $this->database_file;
                    $this->username = null;
                    $this->password = null;
                    break;
            }

            if (
                in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) &&
                $this->charset
            )
            {
                $commands[] = "SET NAMES '" . $this->charset . "'";
            }

            $this->pdo = new PDO(
                $dsn,
                $this->username,
                $this->password,
                $this->option
            );

            foreach ($commands as $value)
            {
                $this->pdo->exec($value);
            }
        }
        catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function query($query)
    {
        if ($this->debug_mode)
        {
            echo $query;

            $this->debug_mode = false;

            return false;
        }

        array_push($this->logs, $query);

        return $this->pdo->query($query);
    }

    public function exec($query)
    {
        if ($this->debug_mode)
        {
            echo $query;

            $this->debug_mode = false;

            return false;
        }

        array_push($this->logs, $query);

        return $this->pdo->exec($query);
    }

    public function quote($string)
    {
        return $this->pdo->quote($string);
    }

    protected function column_quote($string)
    {
        return '"' . str_replace('.', '"."', preg_replace('/(^#|\(JSON\)\s*)/', '', $string)) . '"';
    }

    protected function column_push($columns)
    {
        if ($columns == '*')
        {
            return $columns;
        }

        if (is_string($columns))
        {
            $columns = array($columns);
        }

        $stack = array();

        foreach ($columns as $key => $value)
        {
            preg_match('/([a-zA-Z0-9_\-\.]*)\s*\(([a-zA-Z0-9_\-]*)\)/i', $value, $match);

            if (isset($match[ 1 ], $match[ 2 ]))
            {
                array_push($stack, $this->column_quote( $match[ 1 ] ) . ' AS ' . $this->column_quote( $match[ 2 ] ));
            }
            else
            {
                array_push($stack, $this->column_quote( $value ));
            }
        }

        return implode($stack, ',');
    }

    protected function array_quote($array)
    {
        $temp = array();

        foreach ($array as $value)
        {
            $temp[] = is_int($value) ? $value : $this->pdo->quote($value);
        }

        return implode($temp, ',');
    }

    protected function inner_conjunct($data, $conjunctor, $outer_conjunctor)
    {
        $haystack = array();

        foreach ($data as $value)
        {
            $haystack[] = '(' . $this->data_implode($value, $conjunctor) . ')';
        }

        return implode($outer_conjunctor . ' ', $haystack);
    }

    protected function fn_quote($column, $string)
    {
        return (strpos($column, '#') === 0 && preg_match('/^[A-Z0-9\_]*\([^)]*\)$/', $string)) ?

            $string :

            $this->quote($string);
    }

    protected function data_implode($data, $conjunctor, $outer_conjunctor = null)
    {
        $wheres = array();

        foreach ($data as $key => $value)
        {
            $type = gettype($value);

            if (
                preg_match("/^(AND|OR)(\s+#.*)?$/i", $key, $relation_match) &&
                $type == 'array'
            )
            {
                $wheres[] = 0 !== count(array_diff_key($value, array_keys(array_keys($value)))) ?
                    '(' . $this->data_implode($value, ' ' . $relation_match[ 1 ]) . ')' :
                    '(' . $this->inner_conjunct($value, ' ' . $relation_match[ 1 ], $conjunctor) . ')';
            }
            else
            {
                preg_match('/(#?)([\w\.\-]+)(\[(\>|\>\=|\<|\<\=|\!|\<\>|\>\<|\!?~)\])?/i', $key, $match);
                $column = $this->column_quote($match[ 2 ]);

                if (isset($match[ 4 ]))
                {
                    $operator = $match[ 4 ];

                    if ($operator == '!')
                    {
                        switch ($type)
                        {
                            case 'NULL':
                                $wheres[] = $column . ' IS NOT NULL';
                                break;

                            case 'array':
                                $wheres[] = $column . ' NOT IN (' . $this->array_quote($value) . ')';
                                break;

                            case 'integer':
                            case 'double':
                                $wheres[] = $column . ' != ' . $value;
                                break;

                            case 'boolean':
                                $wheres[] = $column . ' != ' . ($value ? '1' : '0');
                                break;

                            case 'string':
                                $wheres[] = $column . ' != ' . $this->fn_quote($key, $value);
                                break;
                        }
                    }

                    if ($operator == '<>' || $operator == '><')
                    {
                        if ($type == 'array')
                        {
                            if ($operator == '><')
                            {
                                $column .= ' NOT';
                            }

                            if (is_numeric($value[ 0 ]) && is_numeric($value[ 1 ]))
                            {
                                $wheres[] = '(' . $column . ' BETWEEN ' . $value[ 0 ] . ' AND ' . $value[ 1 ] . ')';
                            }
                            else
                            {
                                $wheres[] = '(' . $column . ' BETWEEN ' . $this->quote($value[ 0 ]) . ' AND ' . $this->quote($value[ 1 ]) . ')';
                            }
                        }
                    }

                    if ($operator == '~' || $operator == '!~')
                    {
                        if ($type == 'string')
                        {
                            $value = array($value);
                        }

                        if (!empty($value))
                        {
                            $like_clauses = array();

                            foreach ($value as $item)
                            {
                                if (preg_match('/^(?!%).+(?<!%)$/', $item))
                                {
                                    $item = '%' . $item . '%';
                                }

                                $like_clauses[] = $column . ($operator === '!~' ? ' NOT' : '') . ' LIKE ' . $this->fn_quote($key, $item);
                            }

                            $wheres[] = implode(' OR ', $like_clauses);
                        }
                    }

                    if (in_array($operator, array('>', '>=', '<', '<=')))
                    {
                        if (is_numeric($value))
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $value;
                        }
                        elseif (strpos($key, '#') === 0)
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $this->fn_quote($key, $value);
                        }
                        else
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $this->quote($value);
                        }
                    }
                }
                else
                {
                    switch ($type)
                    {
                        case 'NULL':
                            $wheres[] = $column . ' IS NULL';
                            break;

                        case 'array':
                            $wheres[] = $column . ' IN (' . $this->array_quote($value) . ')';
                            break;

                        case 'integer':
                        case 'double':
                            $wheres[] = $column . ' = ' . $value;
                            break;

                        case 'boolean':
                            $wheres[] = $column . ' = ' . ($value ? '1' : '0');
                            break;

                        case 'string':
                            $wheres[] = $column . ' = ' . $this->fn_quote($key, $value);
                            break;
                    }
                }
            }
        }

        return implode($conjunctor . ' ', $wheres);
    }

    protected function where_clause($where)
    {
        $where_clause = '';

        if (is_array($where))
        {
            $where_keys = array_keys($where);
            $where_AND = preg_grep("/^AND\s*#?$/i", $where_keys);
            $where_OR = preg_grep("/^OR\s*#?$/i", $where_keys);

            $single_condition = array_diff_key($where, array_flip(
                explode(' ', 'AND OR GROUP ORDER HAVING LIMIT LIKE MATCH')
            ));

            if ($single_condition != array())
            {
                $where_clause = ' WHERE ' . $this->data_implode($single_condition, '');
            }

            if (!empty($where_AND))
            {
                $value = array_values($where_AND);
                $where_clause = ' WHERE ' . $this->data_implode($where[ $value[ 0 ] ], ' AND');
            }

            if (!empty($where_OR))
            {
                $value = array_values($where_OR);
                $where_clause = ' WHERE ' . $this->data_implode($where[ $value[ 0 ] ], ' OR');
            }

            if (isset($where[ 'MATCH' ]))
            {
                $MATCH = $where[ 'MATCH' ];

                if (is_array($MATCH) && isset($MATCH[ 'columns' ], $MATCH[ 'keyword' ]))
                {
                    $where_clause .= ($where_clause != '' ? ' AND ' : ' WHERE ') . ' MATCH ("' . str_replace('.', '"."', implode($MATCH[ 'columns' ], '", "')) . '") AGAINST (' . $this->quote($MATCH[ 'keyword' ]) . ')';
                }
            }

            if (isset($where[ 'GROUP' ]))
            {
                $where_clause .= ' GROUP BY ' . $this->column_quote($where[ 'GROUP' ]);

                if (isset($where[ 'HAVING' ]))
                {
                    $where_clause .= ' HAVING ' . $this->data_implode($where[ 'HAVING' ], ' AND');
                }
            }

            if (isset($where[ 'ORDER' ]))
            {
                $rsort = '/(^[a-zA-Z0-9_\-\.]*)(\s*(DESC|ASC))?/';
                $ORDER = $where[ 'ORDER' ];

                if (is_array($ORDER))
                {
                    if (
                        isset($ORDER[ 1 ]) &&
                        is_array($ORDER[ 1 ])
                    )
                    {
                        $where_clause .= ' ORDER BY FIELD(' . $this->column_quote($ORDER[ 0 ]) . ', ' . $this->array_quote($ORDER[ 1 ]) . ')';
                    }
                    else
                    {
                        $stack = array();

                        foreach ($ORDER as $column)
                        {
                            preg_match($rsort, $column, $order_match);

                            array_push($stack, '"' . str_replace('.', '"."', $order_match[ 1 ]) . '"' . (isset($order_match[ 3 ]) ? ' ' . $order_match[ 3 ] : ''));
                        }

                        $where_clause .= ' ORDER BY ' . implode($stack, ',');
                    }
                }
                else
                {
                    preg_match($rsort, $ORDER, $order_match);

                    $where_clause .= ' ORDER BY "' . str_replace('.', '"."', $order_match[ 1 ]) . '"' . (isset($order_match[ 3 ]) ? ' ' . $order_match[ 3 ] : '');
                }
            }

            if (isset($where[ 'LIMIT' ]))
            {
                $LIMIT = $where[ 'LIMIT' ];

                if (is_numeric($LIMIT))
                {
                    $where_clause .= ' LIMIT ' . $LIMIT;
                }

                if (
                    is_array($LIMIT) &&
                    is_numeric($LIMIT[ 0 ]) &&
                    is_numeric($LIMIT[ 1 ])
                )
                {
                    if ($this->database_type === 'pgsql')
                    {
                        $where_clause .= ' OFFSET ' . $LIMIT[ 0 ] . ' LIMIT ' . $LIMIT[ 1 ];
                    }
                    else
                    {
                        $where_clause .= ' LIMIT ' . $LIMIT[ 0 ] . ',' . $LIMIT[ 1 ];
                    }
                }
            }
        }
        else
        {
            if ($where != null)
            {
                $where_clause .= ' ' . $where;
            }
        }

        return $where_clause;
    }

    protected function select_context($table, $join, &$columns = null, $where = null, $column_fn = null)
    {
        $table = '"' . $this->prefix . $table . '"';
        $join_key = is_array($join) ? array_keys($join) : null;

        if (
            isset($join_key[ 0 ]) &&
            strpos($join_key[ 0 ], '[') === 0
        )
        {
            $table_join = array();

            $join_array = array(
                '>' => 'LEFT',
                '<' => 'RIGHT',
                '<>' => 'FULL',
                '><' => 'INNER'
            );

            foreach($join as $sub_table => $relation)
            {
                preg_match('/(\[(\<|\>|\>\<|\<\>)\])?([a-zA-Z0-9_\-]*)\s?(\(([a-zA-Z0-9_\-]*)\))?/', $sub_table, $match);

                if ($match[ 2 ] != '' && $match[ 3 ] != '')
                {
                    if (is_string($relation))
                    {
                        $relation = 'USING ("' . $relation . '")';
                    }

                    if (is_array($relation))
                    {
                        // For ['column1', 'column2']
                        if (isset($relation[ 0 ]))
                        {
                            $relation = 'USING ("' . implode($relation, '", "') . '")';
                        }
                        else
                        {
                            $joins = array();

                            foreach ($relation as $key => $value)
                            {
                                $joins[] = (
                                    strpos($key, '.') > 0 ?
                                        // For ['tableB.column' => 'column']
                                        '"' . str_replace('.', '"."', $key) . '"' :

                                        // For ['column1' => 'column2']
                                        $table . '."' . $key . '"'
                                ) .
                                ' = ' .
                                '"' . (isset($match[ 5 ]) ? $match[ 5 ] : $match[ 3 ]) . '"."' . $value . '"';
                            }

                            $relation = 'ON ' . implode($joins, ' AND ');
                        }
                    }

                    $table_join[] = $join_array[ $match[ 2 ] ] . ' JOIN "' . $match[ 3 ] . '" ' . (isset($match[ 5 ]) ?  'AS "' . $match[ 5 ] . '" ' : '') . $relation;
                }
            }

            $table .= ' ' . implode($table_join, ' ');
        }
        else
        {
            if (is_null($columns))
            {
                if (is_null($where))
                {
                    if (
                        is_array($join) &&
                        isset($column_fn)
                    )
                    {
                        $where = $join;
                        $columns = null;
                    }
                    else
                    {
                        $where = null;
                        $columns = $join;
                    }
                }
                else
                {
                    $where = $join;
                    $columns = null;
                }
            }
            else
            {
                $where = $columns;
                $columns = $join;
            }
        }

        if (isset($column_fn))
        {
            if ($column_fn == 1)
            {
                $column = '1';

                if (is_null($where))
                {
                    $where = $columns;
                }
            }
            else
            {
                if (empty($columns))
                {
                    $columns = '*';
                    $where = $join;
                }

                $column = $column_fn . '(' . $this->column_push($columns) . ')';
            }
        }
        else
        {
            $column = $this->column_push($columns);
        }

        return 'SELECT ' . $column . ' FROM ' . $table . $this->where_clause($where);
    }

    public function select($table, $join, $columns = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $columns, $where));

        return $query ? $query->fetchAll(
            (is_string($columns) && $columns != '*') ? PDO::FETCH_COLUMN : PDO::FETCH_ASSOC
        ) : false;
    }

    public function insert($table, $datas)
    {
        $lastId = array();

        // Check indexed or associative array
        if (!isset($datas[ 0 ]))
        {
            $datas = array($datas);
        }

        foreach ($datas as $data)
        {
            $values = array();
            $columns = array();

            foreach ($data as $key => $value)
            {
                array_push($columns, $this->column_quote($key));

                switch (gettype($value))
                {
                    case 'NULL':
                        $values[] = 'NULL';
                        break;

                    case 'array':
                        preg_match("/\(JSON\)\s*([\w]+)/i", $key, $column_match);

                        $values[] = isset($column_match[ 0 ]) ?
                            $this->quote(json_encode($value)) :
                            $this->quote(serialize($value));
                        break;

                    case 'boolean':
                        $values[] = ($value ? '1' : '0');
                        break;

                    case 'integer':
                    case 'double':
                    case 'string':
                        $values[] = $this->fn_quote($key, $value);
                        break;
                }
            }

            $this->exec('INSERT INTO "' . $this->prefix . $table . '" (' . implode(', ', $columns) . ') VALUES (' . implode($values, ', ') . ')');

            $lastId[] = $this->pdo->lastInsertId();
        }

        return count($lastId) > 1 ? $lastId : $lastId[ 0 ];
    }

    public function update($table, $data, $where = null)
    {
        $fields = array();

        foreach ($data as $key => $value)
        {
            preg_match('/([\w]+)(\[(\+|\-|\*|\/)\])?/i', $key, $match);

            if (isset($match[ 3 ]))
            {
                if (is_numeric($value))
                {
                    $fields[] = $this->column_quote($match[ 1 ]) . ' = ' . $this->column_quote($match[ 1 ]) . ' ' . $match[ 3 ] . ' ' . $value;
                }
            }
            else
            {
                $column = $this->column_quote($key);

                switch (gettype($value))
                {
                    case 'NULL':
                        $fields[] = $column . ' = NULL';
                        break;

                    case 'array':
                        preg_match("/\(JSON\)\s*([\w]+)/i", $key, $column_match);

                        $fields[] = $column . ' = ' . $this->quote(
                                isset($column_match[ 0 ]) ? json_encode($value) : serialize($value)
                            );
                        break;

                    case 'boolean':
                        $fields[] = $column . ' = ' . ($value ? '1' : '0');
                        break;

                    case 'integer':
                    case 'double':
                    case 'string':
                        $fields[] = $column . ' = ' . $this->fn_quote($key, $value);
                        break;
                }
            }
        }

        return $this->exec('UPDATE "' . $this->prefix . $table . '" SET ' . implode(', ', $fields) . $this->where_clause($where));
    }

    public function delete($table, $where)
    {
        return $this->exec('DELETE FROM "' . $this->prefix . $table . '"' . $this->where_clause($where));
    }

    public function replace($table, $columns, $search = null, $replace = null, $where = null)
    {
        if (is_array($columns))
        {
            $replace_query = array();

            foreach ($columns as $column => $replacements)
            {
                foreach ($replacements as $replace_search => $replace_replacement)
                {
                    $replace_query[] = $column . ' = REPLACE(' . $this->column_quote($column) . ', ' . $this->quote($replace_search) . ', ' . $this->quote($replace_replacement) . ')';
                }
            }

            $replace_query = implode(', ', $replace_query);
            $where = $search;
        }
        else
        {
            if (is_array($search))
            {
                $replace_query = array();

                foreach ($search as $replace_search => $replace_replacement)
                {
                    $replace_query[] = $columns . ' = REPLACE(' . $this->column_quote($columns) . ', ' . $this->quote($replace_search) . ', ' . $this->quote($replace_replacement) . ')';
                }

                $replace_query = implode(', ', $replace_query);
                $where = $replace;
            }
            else
            {
                $replace_query = $columns . ' = REPLACE(' . $this->column_quote($columns) . ', ' . $this->quote($search) . ', ' . $this->quote($replace) . ')';
            }
        }

        return $this->exec('UPDATE "' . $this->prefix . $table . '" SET ' . $replace_query . $this->where_clause($where));
    }

    public function get($table, $join = null, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where) . ' LIMIT 1');

        if ($query)
        {
            $data = $query->fetchAll(PDO::FETCH_ASSOC);

            if (isset($data[ 0 ]))
            {
                $column = $where == null ? $join : $column;

                if (is_string($column) && $column != '*')
                {
                    return $data[ 0 ][ $column ];
                }

                return $data[ 0 ];
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public function has($table, $join, $where = null)
    {
        $column = null;

        $query = $this->query('SELECT EXISTS(' . $this->select_context($table, $join, $column, $where, 1) . ')');

        return $query ? $query->fetchColumn() === '1' : false;
    }

    public function count($table, $join = null, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'COUNT'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function max($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'MAX'));

        if ($query)
        {
            $max = $query->fetchColumn();

            return is_numeric($max) ? $max + 0 : $max;
        }
        else
        {
            return false;
        }
    }

    public function min($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'MIN'));

        if ($query)
        {
            $min = $query->fetchColumn();

            return is_numeric($min) ? $min + 0 : $min;
        }
        else
        {
            return false;
        }
    }

    public function avg($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'AVG'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function sum($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'SUM'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function action($actions)
    {
        if (is_callable($actions))
        {
            $this->pdo->beginTransaction();

            $result = $actions($this);

            if ($result === false)
            {
                $this->pdo->rollBack();
            }
            else
            {
                $this->pdo->commit();
            }
        }
        else
        {
            return false;
        }
    }

    public function debug()
    {
        $this->debug_mode = true;

        return $this;
    }

    public function error()
    {
        return $this->pdo->errorInfo();
    }

    public function last_query()
    {
        return end($this->logs);
    }

    public function log()
    {
        return $this->logs;
    }

    public function info()
    {
        $output = array(
            'server' => 'SERVER_INFO',
            'driver' => 'DRIVER_NAME',
            'client' => 'CLIENT_VERSION',
            'version' => 'SERVER_VERSION',
            'connection' => 'CONNECTION_STATUS'
        );

        foreach ($output as $key => $value)
        {
            $output[ $key ] = $this->pdo->getAttribute(constant('PDO::ATTR_' . $value));
        }

        return $output;
    }
}
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值