huwhois 4 سال پیش
والد
کامیت
dc0ee3439d

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+/vendor/

+ 8 - 0
.htaccess

@@ -0,0 +1,8 @@
+<IfModule mod_rewrite.c>
+  Options +FollowSymlinks -Multiviews
+  RewriteEngine On
+
+  RewriteCond %{REQUEST_FILENAME} !-d
+  RewriteCond %{REQUEST_FILENAME} !-f
+  RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
+</IfModule>

+ 0 - 36
README.en.md

@@ -1,36 +0,0 @@
-# hu-mvc
-
-#### Description
-{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**}
-
-#### Software Architecture
-Software architecture description
-
-#### Installation
-
-1.  xxxx
-2.  xxxx
-3.  xxxx
-
-#### Instructions
-
-1.  xxxx
-2.  xxxx
-3.  xxxx
-
-#### Contribution
-
-1.  Fork the repository
-2.  Create Feat_xxx branch
-3.  Commit your code
-4.  Create Pull Request
-
-
-#### Gitee Feature
-
-1.  You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
-2.  Gitee blog [blog.gitee.com](https://blog.gitee.com)
-3.  Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
-4.  The most valuable open source project [GVP](https://gitee.com/gvp)
-5.  The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
-6.  The most popular members  [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)

+ 97 - 27
README.md

@@ -1,39 +1,109 @@
-# hu-mvc
+# mymvc
+从零建MVC框架
 
-#### 介绍
-{**以下是 Gitee 平台说明,您可以替换此简介**
-Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台
-无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)}
+# 框架简单思路
+1. 接收,打印参数想怎么弄。如 获取配置文件的方法,根据传过来的参数 构想
 
-#### 软件架构
-软件架构说明
+2. 一般都是先判断文件是否存在。存在就该include就include,该new就new。然后做存到属性中(做缓存)
 
+3. 主要是调用流程:都什么需要放到run方法中
 
-#### 安装教程
 
-1.  xxxx
-2.  xxxx
-3.  xxxx
+# 具体过程
+## 一 框架启动文件(start.php)
+* 1.定义全局常量(define)(包括环境常量)
+* 2.注册自动加载
+* 3.调用 run 方法
 
-#### 使用说明
+## 二 路由文件(Route.php)
+* 解析 url 获取 model, controller, action 将多余部分转入 get 参数
 
-1.  xxxx
-2.  xxxx
-3.  xxxx
+## 三 加载配置文件
+* 目前只用框架的config.php 未开始模快配置文件, Config 有静态 set 方法可以添改设置
 
-#### 参与贡献
+## 四 找到controller 并实例化, 调用方法
 
-1.  Fork 本仓库
-2.  新建 Feat_xxx 分支
-3.  提交代码
-4.  新建 Pull Request
+## 五 处理并输出结果
+* 使用 Response 类处理输出结果
+> 以上就是该简单框架运行过程, 还没有添加日志, 数据库等过程, 这些后面再慢慢加
 
+# 框架开发文档
 
-#### 特技
+## 目录结构
+初始的目录结构如下:
+~~~
+www  WEB部署目录(或者子目录)
+├─application           应用目录(可以更改)
+│  ├─module_name        模块目录
+│  │  ├─controller      控制器目录
+│  │  ├─model           模型目录
+│  │  └─view            视图目录
+├─daswork               框架系统目录
+│  ├─main               框架类库目录
+│  │  ├─common          公共函数库
+│  │  ├─db              数据驱动库
+│  │  ├─response        响应类库
+│  │  ├─App.php         项目运行类
+│  │  ├─Config.php      设置类
+│  │  ├─Controller.php  控制器类
+│  │  ├─Loader.php      加载类
+│  │  ├─Model.php       模型类
+│  │  ├─Response.php    响应类
+│  │  ├─Route.php       路由类
+│  │  ├─Session.php     session类
+│  │  ├─SqliteModel.php Sqlite类(后面会合并移数据驱动库)
+│  │  └─View.php        视图类
+│  ├─config.php         框架惯例配置文件
+│  ├─helper.php         助手函数文件
+│  ├─service.php        PHP web service 处理url,  实现'mod_rewrite'功能
+│  └─start.php          框架入口文件
+├─public                WEB目录(对外访问目录)
+│  ├─favicon.ico        图标
+│  └─index.php          入口文件
+├─extend                扩展类库目录
+├─runtime               应用的运行时目录(可写,可定制)
+├─vendor                第三方类库目录(Composer依赖库)
+├─build.php             自动生成定义文件(参考)
+├─composer.json         composer 定义文件
+├─LICENSE.txt           授权说明文件
+├─README.md             README 文件
+├─start.bat             项目启动脚本(win)
+├─start.sh              项目启动脚本(unix)
+~~~
 
-1.  使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
-2.  Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
-3.  你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
-4.  [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
-5.  Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
-6.  Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
+> 项目可以使用php 内置的web service, 需要 path_info, 参考 laravel 的方法
+```php
+$uri = urldecode(
+    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
+);
+
+// 这个文件允许我们从内置 PHP web 服务器中模拟 Apache 的 "mod_rewrite" 功能.
+// 这提供了一种测试 Laravel 应用程序的便捷方法,
+// 而无需在此安装"真正的" web 服务器软件。
+if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
+    return false;
+}
+
+require_once __DIR__.'/public/index.php';
+```
+> 启动脚本
+```sh
+cd ./public
+php -S localhost:8000 ../daswork/service.php
+```
+
+## 框架类库(\daswork\mian)
+
+### App.php
+主要是 run 方法:
+新建路由对象 找到控制器 执行方法 输出结果
+```mermaid
+graph LR
+A[方形] -->B(圆角)
+    B --> C{条件a}
+    C -->|a=1| D[结果1]
+    C -->|a=2| E[结果2]
+    F[横向流程图]
+```
+
+### Config.php

+ 34 - 0
application/admin/controller/Index.php

@@ -0,0 +1,34 @@
+<?php
+namespace app\admin\controller;
+
+use daswork\Session;
+use app\admin\model\SendEmail;
+
+Class Index
+{
+    public function index()
+    {
+        echo "This is demo module";
+    }
+
+    public function test()
+    {
+        $session = new Session();
+        $session->set('tt', 12234);
+        echo "ttttt";
+    }
+
+    public function testSession()
+    {
+        $session = new Session();
+        $tt = $session->get('tt');
+        echo $tt;
+    }
+
+    public function testModel()
+    {
+        $model = new SendEmail();
+        // var_dump($model->list());
+        print_json($model->list('limit 10'));
+    }
+}

+ 9 - 0
application/admin/model/SendEmail.php

@@ -0,0 +1,9 @@
+<?php
+namespace app\admin\model;
+
+use daswork\Model;
+
+class SendEmail extends Model
+{
+
+}

+ 19 - 0
application/index/controller/Index.php

@@ -0,0 +1,19 @@
+<?php
+namespace app\index\controller;
+use daswork\Controller;
+use daswork\Config;
+
+class Index extends Controller
+{
+    public function index()
+    {
+        return "Hello World";
+    }
+
+    public function test()
+    {
+        $data = "test--dasdsd";
+        $this->assign('data', $data);
+        return $this->fetch();
+    }
+}

+ 15 - 0
application/index/view/index/test.php

@@ -0,0 +1,15 @@
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
+<title>test</title>
+</head>
+
+<body>
+<!-- <h1>test1</h1>
+<h2>test2</h2>
+<h3>test3</h3> -->
+<div>
+    <?php echo $data;?>
+</div>
+</body>
+</html>

+ 12 - 0
composer.json

@@ -0,0 +1,12 @@
+{
+    "name": "huwhois/mymvc",
+    "description": "..",
+    "license": "Apache License 2.0",
+    "authors": [
+        {
+            "name": "hu huwhois",
+            "email": "huwhois@163.com"
+        }
+    ],
+    "require": {}
+}

+ 27 - 0
daswork/config.php

@@ -0,0 +1,27 @@
+<?php
+return [
+	'mysqlitedb' => DAS_PATH . '/../db/mysqlite.db',
+	'db'  =>[
+		'host'=>'192.168.3.233',
+		'username'=>'root',
+		'passwd'=>'root001',
+		'dbname'=>'test',
+		'hostport'=>'3306',
+		'prefix'=>''
+	],
+	'route' =>[
+		'm'=>'index',
+		'c'=>'Index',
+		'a'=>'index'
+	],
+    'session' => [
+        'id' => '',
+        // SESSION_ID的提交变量,解决flash上传跨域
+        'var_session_id' => '',
+        // 是否自动开启 SESSION
+        'auto_start' => true,
+        'httponly' => true,
+        'secure' => false,
+    ],
+
+];

+ 53 - 0
daswork/helper.php

@@ -0,0 +1,53 @@
+<?php
+// 助手函数
+namespace daswork;
+
+use daswork\Config;
+use daswork\Session;
+
+if (!function_exists('config')) {
+    /**
+     * 获取和设置配置参数
+     * @param string|array  $name 参数名
+     * @param mixed         $value 参数值
+     * @param string        $range 作用域
+     * @return mixed
+     */
+    function config($name = '', $value = null, $range = '')
+    {
+        if (is_null($value) && is_string($name)) {
+            return 0 === strpos($name, '?') ? Config::has(substr($name, 1), $range) : Config::get($name, $range);
+        } else {
+            return Config::set($name, $value, $range);
+        }
+    }
+}
+
+if (!function_exists('session')) {
+    /**
+     * Session管理
+     * @param string|array  $name session名称,如果为数组表示进行session设置
+     * @param mixed         $value session值
+     * @param string        $prefix 前缀
+     * @return mixed
+     */
+    function session($name, $value = '', $prefix = null)
+    {
+        if (is_array($name)) {
+            // 初始化
+            Session::init($name);
+        } elseif (is_null($name)) {
+            // 清除
+            Session::clear('' === $value ? null : $value);
+        } elseif ('' === $value) {
+            // 判断或获取
+            return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix);
+        } elseif (is_null($value)) {
+            // 删除
+            return Session::delete($name, $prefix);
+        } else {
+            // 设置
+            return Session::set($name, $value, $prefix);
+        }
+    }
+}

+ 136 - 0
daswork/main/App.php

@@ -0,0 +1,136 @@
+<?php
+namespace daswork;
+use \daswork\Route;
+use \daswork\Config;
+
+class App{
+    public static $classMap = array();#用于判断类是否存在,节约性能
+ 
+    /**
+     * 运行控制器和方法
+     * @throws \Exception
+     */
+    public static function run(){
+        self::init();
+        $route = new Route();
+        $model = $route->model;
+        $ctrlClass = '\\app\\' . $model  . '\\' . "controller" . '\\'. $route->ctrl;
+        $action = $route->action;
+        $ctrl = new $ctrlClass();
+        $data = $ctrl->$action();
+        // var_dump($data);
+        // is_null($request) && $request = Request::instance();
+
+        // 请求缓存检查
+        // $request->cache($config['request_cache'], $config['request_cache_expire'], $config['request_cache_except']);
+
+        // 输出数据到客户端
+        if ($data instanceof Response) {
+            $response = $data;
+        } elseif (!is_null($data)) {
+            // 默认自动识别响应输出类型
+            // $isAjax   = $request->isAjax();
+            // $type = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type');
+            $type = 'html';
+            $response = Response::create($data, $type);
+        } else {
+            $response = Response::create();
+        }
+
+        $response->send();
+    }
+
+    public static function init()
+    {
+        Config::load();
+    //   return Config::get();  
+    }
+}
+
+
+    // /**
+    //  * 执行应用程序
+    //  * @access public
+    //  * @param Request $request Request对象
+    //  * @return Response
+    //  * @throws Exception
+    //  */
+    // public static function run(Request $request = null)
+    // {
+    //     is_null($request) && $request = Request::instance();
+
+    //     try {
+    //         $config = self::initCommon();
+    //         if (defined('BIND_MODULE')) {
+    //             // 模块/控制器绑定
+    //             BIND_MODULE && Route::bind(BIND_MODULE);
+    //         } elseif ($config['auto_bind_module']) {
+    //             // 入口自动绑定
+    //             $name = pathinfo($request->baseFile(), PATHINFO_FILENAME);
+    //             if ($name && 'index' != $name && is_dir(APP_PATH . $name)) {
+    //                 Route::bind($name);
+    //             }
+    //         }
+
+    //         $request->filter($config['default_filter']);
+
+    //         // 默认语言
+    //         Lang::range($config['default_lang']);
+    //         if ($config['lang_switch_on']) {
+    //             // 开启多语言机制 检测当前语言
+    //             Lang::detect();
+    //         }
+    //         $request->langset(Lang::range());
+
+    //         // 加载系统语言包
+    //         Lang::load([
+    //             THINK_PATH . 'lang' . DS . $request->langset() . EXT,
+    //             APP_PATH . 'lang' . DS . $request->langset() . EXT,
+    //         ]);
+
+    //         // 获取应用调度信息
+    //         $dispatch = self::$dispatch;
+    //         if (empty($dispatch)) {
+    //             // 进行URL路由检测
+    //             $dispatch = self::routeCheck($request, $config);
+    //         }
+    //         // 记录当前调度信息
+    //         $request->dispatch($dispatch);
+
+    //         // 记录路由和请求信息
+    //         if (self::$debug) {
+    //             Log::record('[ ROUTE ] ' . var_export($dispatch, true), 'info');
+    //             Log::record('[ HEADER ] ' . var_export($request->header(), true), 'info');
+    //             Log::record('[ PARAM ] ' . var_export($request->param(), true), 'info');
+    //         }
+
+    //         // 监听app_begin
+    //         Hook::listen('app_begin', $dispatch);
+    //         // 请求缓存检查
+    //         $request->cache($config['request_cache'], $config['request_cache_expire'], $config['request_cache_except']);
+
+    //         $data = self::exec($dispatch, $config);
+    //     } catch (HttpResponseException $exception) {
+    //         $data = $exception->getResponse();
+    //     }
+
+    //     // 清空类的实例化
+    //     Loader::clearInstance();
+
+    //     // 输出数据到客户端
+    //     if ($data instanceof Response) {
+    //         $response = $data;
+    //     } elseif (!is_null($data)) {
+    //         // 默认自动识别响应输出类型
+    //         $isAjax   = $request->isAjax();
+    //         $type     = $isAjax ? Config::get('default_ajax_return') : Config::get('default_return_type');
+    //         $response = Response::create($data, $type);
+    //     } else {
+    //         $response = Response::create();
+    //     }
+
+    //     // 监听app_end
+    //     Hook::listen('app_end', $response);
+
+    //     return $response;
+    // }

+ 92 - 0
daswork/main/Config.php

@@ -0,0 +1,92 @@
+<?php
+namespace daswork;
+
+class Config
+{
+    // 配置参数
+    private static $config = [];
+
+    public static function load($file=''){
+        if(is_file($file)) {
+            self::$config = include_once($file);
+        } else {
+            self::$config = include_once(DAS_PATH . DS . 'config.php');
+        }
+	}
+
+    /**
+     * 获取配置参数 为空则获取所有配置
+     * @param string    $name 配置参数名(支持二级配置 .号分割)
+     * @return mixed
+     */
+    public static function get($name='')
+    {
+        if ($name) {
+            return self::$config[$name];
+        } else {
+            return self::$config;
+        }
+    }
+
+    /**
+     * 检测配置是否存在
+     * @param string    $name 配置参数名(支持二级配置 .号分割)
+     * @return bool
+     */
+    public static function has($name)
+    {
+
+        if (!strpos($name, '.')) {
+            return isset(self::$config[strtolower($name)]);
+        } else {
+            // 二维数组设置和获取支持
+            $name = explode('.', $name, 2);
+            return isset(self::$config[strtolower($name[0])][$name[1]]);
+        }
+    }
+
+    /**
+     * 设置配置参数 name为数组则为批量设置
+     * @param string|array  $name 配置参数名(支持二级配置 .号分割)
+     * @param mixed         $value 配置值
+     * @param string        $range  作用域
+     * @return mixed
+     */
+    public static function set($name, $value = null)
+    {
+        if (!isset(self::$config)) {
+            self::$config = [];
+        }
+        if (is_string($name)) {
+            if (!strpos($name, '.')) {
+                self::$config[strtolower($name)] = $value;
+            } else {
+                // 二维数组设置和获取支持
+                $name                                                 = explode('.', $name, 2);
+                self::$config[strtolower($name[0])][$name[1]] = $value;
+            }
+            return;
+        } elseif (is_array($name)) {
+            // 批量设置
+            if (!empty($value)) {
+                self::$config[$value] = isset(self::$config[$value]) ?
+                array_merge(self::$config[$value], $name) :
+                self::$config[$value] = $name;
+                return self::$config[$value];
+            } else {
+                return self::$config = array_merge(self::$config, array_change_key_case($name));
+            }
+        } else {
+            // 为空直接返回 已有配置
+            return self::$config;
+        }
+    }
+
+    /**
+     * 重置配置参数
+     */
+    public static function reset()
+    {
+        self::$config = [];
+    }
+}

+ 23 - 0
daswork/main/Controller.php

@@ -0,0 +1,23 @@
+<?php
+namespace daswork;
+
+use daswork\View;
+
+class Controller
+{ 	
+	protected $view;
+
+	public function __construct(){
+		$this->view = new View();
+	}
+	
+	public function fetch($file=""){
+
+		return $this->view->fetch();
+	}
+
+	public function assign($name,$value)
+	{
+		$this->view->assign($name, $value);
+	}
+}

+ 82 - 0
daswork/main/Loader.php

@@ -0,0 +1,82 @@
+<?php
+namespace daswork;
+
+class Loader 
+{
+    // protected static $instance = [];
+    // 类名映射
+    // protected static $map = [];
+    // 命名空间别名
+    // protected static $namespaces = [];
+    // 自动加载的文件
+    // private static $autoloadFiles = [];
+    // 命名空间与路径映射
+    private static $namespaces = [];
+    // 已加载过的class
+    protected static $classMap = [];
+
+    // 自动加载
+    private static function autoload($class)
+    {
+        // 是否有加载过
+        if (in_array($class, self::$classMap)) {
+            return true;
+        }
+
+        if ($file = self::findFile($class)) {
+            // Win环境严格区分大小写
+            if (IS_WIN && pathinfo($file, PATHINFO_FILENAME) != pathinfo(realpath($file), PATHINFO_FILENAME)) {
+                return false;
+            }
+            __include_file($file);
+            $classMap[] = $class;
+            return true;
+        }
+    }
+    
+    public static function findFile($class)
+    {
+        $namespace = \dirname($class);
+        // 有命名空间映射的  
+        if (isset(self::$namespaces[$namespace])) {
+            $file = self::$namespaces[$namespace] . basename($class) . EXT;
+            return $file;
+        }
+        // var_dump($class);
+        // var_dump(substr($class,strpos($class, '\\') + 1));
+        $model = substr($class,0,strpos($class, '\\'));
+        // var_dump($model);
+        if ($model=='app') {
+            $file = APP_PATH . DS. str_replace('\\', DS, substr($class,strpos($class, '\\') + 1)) . EXT;
+            // var_dump($file);
+            return $file;
+        }
+    }
+
+    // 注册系统自动加载
+    public static function register($autoload = '')
+    {
+        spl_autoload_register($autoload ?: 'daswork\\Loader::autoload', true, true);
+        self::$namespaces = [
+            'daswork' => CORE_PATH,
+            'daswork\db' => CORE_PATH . 'db' . DS
+        ];
+    }
+}
+
+/**
+ * 作用范围隔离
+ *
+ * @param $file
+ * @return mixed
+ */
+function __include_file($file)
+{
+    return include $file;
+}
+
+function __require_file($file)
+{
+    return require $file;
+}
+

+ 389 - 0
daswork/main/Model.php

@@ -0,0 +1,389 @@
+<?php
+namespace daswork;
+
+use daswork\Config;
+use daswork\db\Mysql;
+
+class Model 
+{
+	// 查询次数
+	public static $queryTimes = 0;
+	// 执行次数
+	public static $executeTimes = 0;	
+    // 数据库连接参数配置
+    protected $connection = [];
+	// 数据库查询对象池
+	protected static $links = [];
+	// 当前类名称
+	protected $class;
+	// 当前模型名称
+	protected $name;
+	// 当前查询对象
+    protected $query;
+    // 当前数据表名称(含前缀)
+    protected $tablename = '';
+    // 当前数据表名称(不含前缀)
+    protected $table = '';
+    // 当前数据表主键
+    protected $pk;
+    // 当前数据表前缀
+    protected $prefix = '';
+    // 查询参数
+    protected $options = [];
+    // 最近查询的 sql 语句
+    public $sql = '';
+	/**
+     * 初始化过的模型.
+     *
+     * @var array
+     */
+    protected static $initialized = [];
+
+	public function __construct()
+	{
+		// 当前类名
+		$this->class = get_called_class();
+
+		if (empty($this->name)) {
+			// 当前模型名
+			$name = str_replace('\\', '/', $this->class);
+			$this->name = basename($name);
+        }
+        
+        // 合并数据库配置
+        if (!empty($this->connection) && is_array($this->connection)) {
+            $connection = array_merge(Config::get('db'), $this->connection);
+        } else {
+            $connection = Config::get('db');
+        }
+    
+        $this->connection = $connection;
+
+        // 设置当前数据表和模型名
+        if (isset($connection['prefix'])) {
+            $this->prefix = $connection['prefix'];
+        }
+        if (!empty($this->table)) {
+            $this->tablename = $this->prefix .  $this->table;
+        } else {
+            $this->tablename = $this->prefix . uncamelize($this->name);
+        }
+
+		// 执行初始化操作
+		$this->initialize();
+    }
+    
+    /**
+     *  初始化模型
+     * @access protected
+     * @return void
+     */
+    protected function initialize()
+    {
+        $class = get_class($this);
+        if (!isset(static::$initialized[$class])) {
+            static::$initialized[$class] = true;
+            static::init();
+        }
+	}
+	
+	/**
+     * 初始化处理
+     * @access protected
+     * @return void
+     */
+    protected static function init()
+    {
+    }
+
+    /**
+     * 获取当前模型的查询对象
+     * @access public
+     * @param bool      $buildNewQuery  创建新的查询对象
+     * @return Query
+     */
+    public function getQuery($buildNewQuery = false)
+    {
+        if ($buildNewQuery) {
+            return Mysql::connect($this->connection);
+        } elseif (!isset(self::$links[$this->class])) {
+            // 创建模型查询对象
+            self::$links[$this->class] = Mysql::connect($this->connection);
+        }
+
+        return self::$links[$this->class];
+    }
+
+    /**
+     * 指定默认数据表名(含前缀)
+     * @access public
+     * @param string $table 表名
+     * @return $this
+     */
+    public function setTablename($tablename)
+    {
+        $this->tablename = $tablename;
+    }
+
+    /**
+     * 得到当前或者指定名称的数据表
+     * @access public
+     * @param string $name
+     * @return string
+     */
+    public function getTablename()
+    {
+        return $this->tablename;
+    }
+
+	/**
+     * 执行sql
+     * @param string $sql
+     * @return mixd $res
+     */
+    public function exec($sql)
+    {
+        @$res = $this->getQuery()->exec($sql);
+        $this->$sql = $sql;
+        return $res;
+    }
+
+    public function query($sql)
+    {
+        $result = $this->getQuery()->query($sql);
+        $this->$sql = $sql;
+        return $result;
+    }
+    
+    public function lastInsertRowID ()
+    {
+        $result = $this->getQuery()->lastInsertRowID();
+        return $result;
+    }
+
+    public function lastErrorMsg()
+    {
+        return $this->getQuery()->lastErrorMsg();
+    }
+
+    /**
+     * 查询数组列表
+     */
+    public function select($sql)
+    {
+        $result = $this->getQuery()->query($sql);
+        $data = array();
+        while ($arr = $result->fetch_assoc()) {
+            $data[] = $arr;
+        }
+        return $data;
+    }
+
+    /**
+     * 列表结果集
+     */
+    public function list($where='')
+    {
+        $sql = "select * from $this->tablename $where;";
+        return $this->select($sql);
+    }
+
+    /**
+     * 查询一条
+     */
+    public function getOneById($id, $tablename='')
+    {
+        $tablename = $tablename ? $tablename : $this->tablename;
+        $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";
+        $result = $this->getQuery()->query($sql);
+        // var_dump($result);
+        $data = $result->fetch_all(MYSQLI_ASSOC);
+        // var_dump($data);
+        return $data;
+    }
+
+    /**
+     * 单列合计
+     */
+    public function sumColumn($column, $tablename)
+    {
+        $tablename = $tablename ? $tablename : $this->tablename;
+        $sql = "SELECT sum(`$column`) as sumData FROM `$tablename`;";
+        $result = $this->getQuery()->query($sql);
+        // $data = $result->fetch_assoc();
+        // var_dump($data['sumData']);exit;
+        if ($data = $result->fetch_assoc()) {
+            return $data['sumData'];
+        }
+        return 0;
+    }
+
+    public function listByName($name='', $order = '', $desc = false)
+    {
+        $where = "";
+        if ($name) {
+            $where = " where name like '%$name%'";
+        }
+
+        if ($order) {
+            $where .= " order by $order";
+            if ($desc) {
+                $where .= " desc";
+            } else {
+                $where .= " asc";
+            }
+        }
+        $sql = "select * from $this->tablename $where;";
+        $res = $this->select($sql);
+
+        return $res;
+    }
+
+    /**
+     * save
+     */
+    public function save($data)
+    {
+        $columns = "";
+        $values = "";
+        foreach ($data as $key => $value) {
+            $columns .=  "`" . $key . "`,";
+            $values .=  "'" . $value . "',";
+        }
+        $columns = rtrim($columns, ',');
+        $values = rtrim($values, ',');
+        $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";
+        return $this->exec($sql);
+    }
+    
+    /**
+     * updateById
+     */
+    public function updateById($data)
+    {
+        $id = $data['id'];
+        unset($data['id']);
+        $columns = "";
+        foreach ($data as $key => $value) {
+            $columns .= "`" . $key . "`='" . $value ."',";
+        }
+        $columns = rtrim($columns, ',');
+        $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";
+        return $this->exec($sql);
+    }
+
+    /**
+     * deleteByIds
+     */
+    public function deleteById($id)
+    {
+        $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";
+        if (is_array($id)) {
+            for ($i=0; $i < count($id); $i++) { 
+                $sql .= $id[$i] . ',';
+            }
+            $sql = rtrim($sql, ',');
+            $sql .= ");";
+        } else {
+            $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";
+        }
+        return $this->exec($sql);
+    }
+
+    // public function __destruct()
+    // {
+    //     $this->query->close();
+    // }
+
+
+	function add($data){
+		
+		//列名数组
+		$cols=array();
+		//列值数组
+		$vals=array();
+		
+		foreach($data as $key=>$val){
+			$cols[]="`".$key."`"; 
+			$vals[]="'".$val."'";
+		}
+		
+		//$cols=array(0=>'`titlekey`',1=>'`contentkey`'); //
+		//$vals=array(0=>"'titleval'",1=>"'contentval'"); //
+		
+		
+		//用","将数组每个元素重新拼接起来
+		$str_cols=implode(',',$cols);  //$str_cols=  `titlekey`,`contentkey` 
+		$str_vals=implode(',',$vals);  //$str_vals=  'titleval','contentval'
+		
+		//执行插入数据
+		$sql="insert into ".$this->tablename."($str_cols) values($str_vals);";
+		
+		return $this->getQuery()->insert($sql );
+	}
+	
+	
+	function update($data,$where){
+		
+		
+		$wherestr = '';
+		if(!empty($where)){
+			$wherestr .=' where '.$where;
+		}
+		
+		$par_array=array();
+		foreach($data as $key=>$val){
+			$par_array[]="`".$key."`="."'".$val."'";
+		}
+		
+		//用","将修改列和列值的数组里每个元素重新拼接起来
+		$param=implode(',',$par_array); 
+			
+		$sql = "update ".$this->tablename." set ".$param." ".$wherestr." ";
+		
+		return $this->getQuery()->query($sql);
+		
+	}
+	
+	function get_lists($where, $limit=''){
+		
+		$wherestr = '';
+		if(!empty($where)){
+			$wherestr .=' where '.$where;
+		}
+		$sql = 'select * from '.$this->tablename.$wherestr . $limit;
+//		echo $sql;
+		return $this->getQuery()->select($sql);
+	}
+
+	function get_sum($where){
+		$wherestr = '';
+		if(!empty($where)){
+			$wherestr .=' where '.$where;
+		}
+		
+		$sql = "select count(*) as sum from ".$this->tablename.$wherestr;
+		
+		$data = $this->getQuery()->get_row($sql);
+		
+		return $data['sum'];
+	}
+	
+	
+	
+	function get_one($where){
+		
+		$wherestr = '';
+		if(!empty($where)){
+			$wherestr .=' where '.$where;
+		}
+		
+		$sql = "select * from ".$this->tablename.$wherestr;
+		
+		//var_dump($sql);exit;
+		
+		$data = $this->getQuery()->get_row($sql);
+		
+		return $data;
+	}
+}

+ 313 - 0
daswork/main/Response.php

@@ -0,0 +1,313 @@
+<?php
+namespace daswork;
+
+// use daswork\response\Json as JsonResponse;
+// use daswork\response\Jsonp as JsonpResponse;
+// use daswork\response\Redirect as RedirectResponse;
+// use daswork\response\View as ViewResponse;
+// use daswork\response\Xml as XmlResponse;
+
+class Response
+{
+    // 原始数据
+    protected $data;
+
+    // 当前的contentType
+    protected $contentType = 'text/html';
+
+    // 字符集
+    protected $charset = 'utf-8';
+
+    //状态
+    protected $code = 200;
+
+    // 输出参数
+    protected $options = [];
+    // header参数
+    protected $header = [];
+
+    protected $content = null;
+
+    /**
+     * 构造函数
+     * @access   public
+     * @param mixed $data    输出数据
+     * @param int   $code
+     * @param array $header
+     * @param array $options 输出参数
+     */
+    public function __construct($data = '', $code = 200, array $header = [], $options = [])
+    {
+        $this->data($data);
+        if (!empty($options)) {
+            $this->options = array_merge($this->options, $options);
+        }
+        $this->contentType($this->contentType, $this->charset);
+        $this->header = array_merge($this->header, $header);
+        $this->code = $code;
+    }
+
+    /**
+     * 创建Response对象
+     * @access public
+     * @param mixed  $data    输出数据
+     * @param string $type    输出类型
+     * @param int    $code
+     * @param array  $header
+     * @param array  $options 输出参数
+     * @return Response|JsonResponse|ViewResponse|XmlResponse|RedirectResponse|JsonpResponse
+     */
+    public static function create($data = '', $type = '', $code = 200, array $header = [], $options = [])
+    {
+        $type = empty($type) ? 'null' : strtolower($type);
+
+        $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst($type);
+        if (class_exists($class)) {
+            $response = new $class($data, $code, $header, $options);
+        } else {
+            $response = new static($data, $code, $header, $options);
+        }
+        
+        return $response;
+    }
+
+    /**
+     * 发送数据到客户端
+     * @access public
+     * @return mixed
+     * @throws \InvalidArgumentException
+     */
+    public function send()
+    {
+        // 处理输出数据
+        $data = $this->getContent();
+
+        // if (200 == $this->code) {
+        //     $cache = Request::instance()->getCache();
+        //     if ($cache) {
+        //         $this->header['Cache-Control'] = 'max-age=' . $cache[1] . ',must-revalidate';
+        //         $this->header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT';
+        //         $this->header['Expires']       = gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $cache[1]) . ' GMT';
+        //         Cache::set($cache[0], [$data, $this->header], $cache[1]);
+        //     }
+        // }
+
+        if (!headers_sent() && !empty($this->header)) {
+            // 发送状态码
+            http_response_code($this->code);
+            // 发送头部信息
+            foreach ($this->header as $name => $val) {
+                if (is_null($val)) {
+                    header($name);
+                } else {
+                    header($name . ':' . $val);
+                }
+            }
+        }
+
+        echo $data;
+
+        if (function_exists('fastcgi_finish_request')) {
+            // 提高页面响应
+            fastcgi_finish_request();
+        }
+
+        // // 清空当次请求有效的数据
+        // if (!($this instanceof RedirectResponse)) {
+        //     Session::flush();
+        // }
+    }
+
+    /**
+     * 处理数据
+     * @access protected
+     * @param mixed $data 要处理的数据
+     * @return mixed
+     */
+    protected function output($data)
+    {
+        return $data;
+    }
+
+    /**
+     * 输出的参数
+     * @access public
+     * @param mixed $options 输出参数
+     * @return $this
+     */
+    public function options($options = [])
+    {
+        $this->options = array_merge($this->options, $options);
+        return $this;
+    }
+
+    /**
+     * 输出数据设置
+     * @access public
+     * @param mixed $data 输出数据
+     * @return $this
+     */
+    public function data($data)
+    {
+        $this->data = $data;
+        return $this;
+    }
+
+    /**
+     * 设置响应头
+     * @access public
+     * @param string|array $name  参数名
+     * @param string       $value 参数值
+     * @return $this
+     */
+    public function header($name, $value = null)
+    {
+        if (is_array($name)) {
+            $this->header = array_merge($this->header, $name);
+        } else {
+            $this->header[$name] = $value;
+        }
+        return $this;
+    }
+
+    /**
+     * 设置页面输出内容
+     * @param $content
+     * @return $this
+     */
+    public function content($content)
+    {
+        if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
+            $content,
+            '__toString',
+        ])
+        ) {
+            throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
+        }
+
+        $this->content = (string) $content;
+
+        return $this;
+    }
+
+    /**
+     * 发送HTTP状态
+     * @param integer $code 状态码
+     * @return $this
+     */
+    public function code($code)
+    {
+        $this->code = $code;
+        return $this;
+    }
+
+    /**
+     * LastModified
+     * @param string $time
+     * @return $this
+     */
+    public function lastModified($time)
+    {
+        $this->header['Last-Modified'] = $time;
+        return $this;
+    }
+
+    /**
+     * Expires
+     * @param string $time
+     * @return $this
+     */
+    public function expires($time)
+    {
+        $this->header['Expires'] = $time;
+        return $this;
+    }
+
+    /**
+     * ETag
+     * @param string $eTag
+     * @return $this
+     */
+    public function eTag($eTag)
+    {
+        $this->header['ETag'] = $eTag;
+        return $this;
+    }
+
+    /**
+     * 页面缓存控制
+     * @param string $cache 状态码
+     * @return $this
+     */
+    public function cacheControl($cache)
+    {
+        $this->header['Cache-control'] = $cache;
+        return $this;
+    }
+
+    /**
+     * 页面输出类型
+     * @param string $contentType 输出类型
+     * @param string $charset     输出编码
+     * @return $this
+     */
+    public function contentType($contentType, $charset = 'utf-8')
+    {
+        $this->header['Content-Type'] = $contentType . '; charset=' . $charset;
+        return $this;
+    }
+
+    /**
+     * 获取头部信息
+     * @param string $name 头部名称
+     * @return mixed
+     */
+    public function getHeader($name = '')
+    {
+        if (!empty($name)) {
+            return isset($this->header[$name]) ? $this->header[$name] : null;
+        } else {
+            return $this->header;
+        }
+    }
+
+    /**
+     * 获取原始数据
+     * @return mixed
+     */
+    public function getData()
+    {
+        return $this->data;
+    }
+
+    /**
+     * 获取输出数据
+     * @return mixed
+     */
+    public function getContent()
+    {
+        if (null == $this->content) {
+            $content = $this->output($this->data);
+
+            if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable([
+                $content,
+                '__toString',
+            ])
+            ) {
+                throw new \InvalidArgumentException(sprintf('variable type error: %s', gettype($content)));
+            }
+
+            $this->content = (string) $content;
+        }
+        return $this->content;
+    }
+
+    /**
+     * 获取状态码
+     * @return integer
+     */
+    public function getCode()
+    {
+        return $this->code;
+    }
+}

+ 58 - 0
daswork/main/Route.php

@@ -0,0 +1,58 @@
+<?php
+namespace daswork;
+use daswork\Config;
+
+class Route{
+    public $model; # 模块
+    public $ctrl; # 控制器
+    public $action; #方法
+    public function __construct()
+    {
+        // xx.com/index.php/index/index
+        // xx.com/index/index
+        /**
+         * 1.隐藏index.php文件,引入.htaccess文件,与入口文件同级
+         * 2.获取URL 参数部分,即get传值
+         * 3.返回对应模块,控制器和方法
+         */
+        $route = Config::get('route');
+
+        if (isset($_SERVER['REQUEST_URI'])&& $_SERVER['REQUEST_URI'] != '/'){
+            $path = $_SERVER['REQUEST_URI'];
+            $pathArr = explode('/',trim($path,'/'));//数组
+            if (isset($pathArr[0])) {
+                $this->model = $pathArr[0];
+                unset($pathArr[0]);
+            }
+            if (isset($pathArr[1])){
+                $this->ctrl = ucfirst(camelize($pathArr[1]));
+                unset($pathArr[1]);
+            } else {
+                $this->ctrl = $route['c'];
+            }
+            if (isset($pathArr[2])){
+                $this->action = camelize($pathArr[2]);
+                unset($pathArr[2]);
+            }else{
+                $this->action = $route['a'];
+            }
+            //url 多余部分转换成GET eg:index/index/id/1 实现get传值
+            $count = count($pathArr) + 2;
+            $i = 2;
+            while ($i < $count){
+                if (isset($pathArr[$i+1])){
+                    $_GET[$pathArr[$i]] = $pathArr[$i+1];
+                }
+                $i = $i + 2;
+            };
+        }else{
+            $this->model = $route['m'];
+            $this->ctrl = $route['c'];
+            $this->action = $route['a'];
+        }
+
+        $GLOBALS['model'] = $this->model;
+        $GLOBALS['ctrl'] = $this->ctrl;
+        $GLOBALS['action'] = $this->action;
+    }
+}

+ 345 - 0
daswork/main/Session.php

@@ -0,0 +1,345 @@
+<?php
+// +----------------------------------------------------------------------
+// | ThinkPHP [ WE CAN DO IT JUST THINK ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Author: liu21st <liu21st@gmail.com>
+// +----------------------------------------------------------------------
+
+namespace daswork;
+
+// use think\exception\ClassNotFoundException;
+
+class Session
+{
+    protected static $prefix = '';
+    protected static $init   = null;
+
+    /**
+     * 设置或者获取session作用域(前缀)
+     * @param string $prefix
+     * @return string|void
+     */
+    public static function prefix($prefix = '')
+    {
+        if (empty($prefix) && null !== $prefix) {
+            return self::$prefix;
+        } else {
+            self::$prefix = $prefix;
+        }
+    }
+
+    /**
+     * session初始化
+     * @param array $config
+     * @return void
+     * @throws \think\Exception
+     */
+    public static function init(array $config = [])
+    {
+        if (empty($config)) {
+            $config = Config::get('session');
+        }
+
+        $isDoStart = false;
+
+        // 启动session
+        if (!empty($config['auto_start']) && PHP_SESSION_ACTIVE != session_status()) {
+            ini_set('session.auto_start', 0);
+            $isDoStart = true;
+        }
+        if (isset($config['var_session_id']) && isset($_REQUEST[$config['var_session_id']])) {
+            session_id($_REQUEST[$config['var_session_id']]);
+        } elseif (isset($config['id']) && !empty($config['id'])) {
+            session_id($config['id']);
+        }
+        if (isset($config['path'])) {
+            session_save_path($config['path']);
+        }
+        if (isset($config['domain'])) {
+            ini_set('session.cookie_domain', $config['domain']);
+        }
+        if (isset($config['expire'])) {
+            ini_set('session.gc_maxlifetime', $config['expire']);
+            ini_set('session.cookie_lifetime', $config['expire']);
+        }
+        if (isset($config['secure'])) {
+            ini_set('session.cookie_secure', $config['secure']);
+        }
+        if (isset($config['httponly'])) {
+            ini_set('session.cookie_httponly', $config['httponly']);
+        }
+        if (isset($config['use_cookies'])) {
+            ini_set('session.use_cookies', $config['use_cookies'] ? 1 : 0);
+        }
+        if (isset($config['cache_limiter'])) {
+            session_cache_limiter($config['cache_limiter']);
+        }
+        if (isset($config['cache_expire'])) {
+            session_cache_expire($config['cache_expire']);
+        }
+        if ($isDoStart) {
+            session_start();
+            self::$init = true;
+        } else {
+            self::$init = false;
+        }
+    }
+
+    /**
+     * session自动启动或者初始化
+     * @return void
+     */
+    public static function boot()
+    {
+        if (is_null(self::$init)) {
+            self::init();
+        } elseif (false === self::$init) {
+            if (PHP_SESSION_ACTIVE != session_status()) {
+                session_start();
+            }
+            self::$init = true;
+        }
+    }
+
+    /**
+     * session设置
+     * @param string        $name session名称
+     * @param mixed         $value session值
+     * @param string|null   $prefix 作用域(前缀)
+     * @return void
+     */
+    public static function set($name, $value = '', $prefix = null)
+    {
+        empty(self::$init) && self::boot();
+
+        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
+        if (strpos($name, '.')) {
+            // 二维数组赋值
+            list($name1, $name2) = explode('.', $name);
+            if ($prefix) {
+                $_SESSION[$prefix][$name1][$name2] = $value;
+            } else {
+                $_SESSION[$name1][$name2] = $value;
+            }
+        } elseif ($prefix) {
+            $_SESSION[$prefix][$name] = $value;
+        } else {
+            $_SESSION[$name] = $value;
+        }
+    }
+
+    /**
+     * session获取
+     * @param string        $name session名称
+     * @param string|null   $prefix 作用域(前缀)
+     * @return mixed
+     */
+    public static function get($name = '', $prefix = null)
+    {
+        empty(self::$init) && self::boot();
+        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
+        if ('' == $name) {
+            // 获取全部的session
+            $value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : []) : $_SESSION;
+        } elseif ($prefix) {
+            // 获取session
+            if (strpos($name, '.')) {
+                list($name1, $name2) = explode('.', $name);
+                $value               = isset($_SESSION[$prefix][$name1][$name2]) ? $_SESSION[$prefix][$name1][$name2] : null;
+            } else {
+                $value = isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null;
+            }
+        } else {
+            if (strpos($name, '.')) {
+                list($name1, $name2) = explode('.', $name);
+                $value               = isset($_SESSION[$name1][$name2]) ? $_SESSION[$name1][$name2] : null;
+            } else {
+                $value = isset($_SESSION[$name]) ? $_SESSION[$name] : null;
+            }
+        }
+        return $value;
+    }
+
+    /**
+     * session获取并删除
+     * @param string        $name session名称
+     * @param string|null   $prefix 作用域(前缀)
+     * @return mixed
+     */
+    public static function pull($name, $prefix = null)
+    {
+        $result = self::get($name, $prefix);
+        if ($result) {
+            self::delete($name, $prefix);
+            return $result;
+        } else {
+            return;
+        }
+    }
+
+    /**
+     * session设置 下一次请求有效
+     * @param string        $name session名称
+     * @param mixed         $value session值
+     * @param string|null   $prefix 作用域(前缀)
+     * @return void
+     */
+    public static function flash($name, $value)
+    {
+        self::set($name, $value);
+        if (!self::has('__flash__.__time__')) {
+            self::set('__flash__.__time__', $_SERVER['REQUEST_TIME_FLOAT']);
+        }
+        self::push('__flash__', $name);
+    }
+
+    /**
+     * 清空当前请求的session数据
+     * @return void
+     */
+    public static function flush()
+    {
+        if (self::$init) {
+            $item = self::get('__flash__');
+
+            if (!empty($item)) {
+                $time = $item['__time__'];
+                if ($_SERVER['REQUEST_TIME_FLOAT'] > $time) {
+                    unset($item['__time__']);
+                    self::delete($item);
+                    self::set('__flash__', []);
+                }
+            }
+        }
+    }
+
+    /**
+     * 删除session数据
+     * @param string|array  $name session名称
+     * @param string|null   $prefix 作用域(前缀)
+     * @return void
+     */
+    public static function delete($name, $prefix = null)
+    {
+        empty(self::$init) && self::boot();
+        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
+        if (is_array($name)) {
+            foreach ($name as $key) {
+                self::delete($key, $prefix);
+            }
+        } elseif (strpos($name, '.')) {
+            list($name1, $name2) = explode('.', $name);
+            if ($prefix) {
+                unset($_SESSION[$prefix][$name1][$name2]);
+            } else {
+                unset($_SESSION[$name1][$name2]);
+            }
+        } else {
+            if ($prefix) {
+                unset($_SESSION[$prefix][$name]);
+            } else {
+                unset($_SESSION[$name]);
+            }
+        }
+    }
+
+    /**
+     * 清空session数据
+     * @param string|null   $prefix 作用域(前缀)
+     * @return void
+     */
+    public static function clear($prefix = null)
+    {
+        empty(self::$init) && self::boot();
+        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
+        if ($prefix) {
+            unset($_SESSION[$prefix]);
+        } else {
+            $_SESSION = [];
+        }
+    }
+
+    /**
+     * 判断session数据
+     * @param string        $name session名称
+     * @param string|null   $prefix
+     * @return bool
+     */
+    public static function has($name, $prefix = null)
+    {
+        empty(self::$init) && self::boot();
+        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
+        if (strpos($name, '.')) {
+            // 支持数组
+            list($name1, $name2) = explode('.', $name);
+            return $prefix ? isset($_SESSION[$prefix][$name1][$name2]) : isset($_SESSION[$name1][$name2]);
+        } else {
+            return $prefix ? isset($_SESSION[$prefix][$name]) : isset($_SESSION[$name]);
+        }
+    }
+
+    /**
+     * 添加数据到一个session数组
+     * @param  string  $key
+     * @param  mixed   $value
+     * @return void
+     */
+    public static function push($key, $value)
+    {
+        $array = self::get($key);
+        if (is_null($array)) {
+            $array = [];
+        }
+        $array[] = $value;
+        self::set($key, $array);
+    }
+
+    /**
+     * 启动session
+     * @return void
+     */
+    public static function start()
+    {
+        session_start();
+        self::$init = true;
+    }
+
+    /**
+     * 销毁session
+     * @return void
+     */
+    public static function destroy()
+    {
+        if (!empty($_SESSION)) {
+            $_SESSION = [];
+        }
+        session_unset();
+        session_destroy();
+        self::$init = null;
+    }
+
+    /**
+     * 重新生成session_id
+     * @param bool $delete 是否删除关联会话文件
+     * @return void
+     */
+    private static function regenerate($delete = false)
+    {
+        session_regenerate_id($delete);
+    }
+
+    /**
+     * 暂停session
+     * @return void
+     */
+    public static function pause()
+    {
+        // 暂停session
+        session_write_close();
+        self::$init = false;
+    }
+}

+ 180 - 0
daswork/main/SqliteModel.php

@@ -0,0 +1,180 @@
+<?php
+namespace daswork\db;
+
+use daswork\Config;
+
+class MySqlite
+{
+    private $mydb;
+    protected $tablename;
+
+    public function __construct($filepath='')
+    {
+        $filepath = $filepath ? $filepath : Config::get('mysqlitedb');
+        $mydb = new \SQLite3('');
+        if (!$mydb) {
+            throw new \Exception("$mydb->lastErrorMsg()", 1);
+        } else {
+            // echo "Opened database successfully\n";
+            $this->mydb = $mydb;
+        }
+    }
+
+    /**
+     * 执行sql
+     * @param string $sql
+     * @return mixd $res
+     */
+    public function exec($sql)
+    {
+        @$res = $this->mydb->exec($sql);
+        return $res;
+    }
+
+    public function query($sql)
+    {
+        $result = $this->mydb->query($sql);
+        return $result;
+    }
+    
+    public function lastInsertRowID ()
+    {
+        $result = $this->mydb->lastInsertRowID();
+        return $result;
+    }
+
+    public function lastErrorMsg()
+    {
+        return $this->mydb->lastErrorMsg();
+    }
+
+    /**
+     * 查询数组列表
+     */
+    public function select($sql)
+    {
+        $result = $this->mydb->query($sql);
+        $data = array();
+        // var_dump($result);exit;
+        while ($arr = $result->fetchArray(SQLITE3_ASSOC)) {
+            $data[] = $arr;
+        }
+        return $data;
+    }
+
+    /**
+     * 查询一条
+     */
+    public function getOneById($id, $tablename='')
+    {
+        $tablename = $tablename ? $tablename : $this->tablename;
+        $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";
+        $result = $this->mydb->query($sql);
+        // var_dump($result);
+        $data = $result->fetchArray(SQLITE3_ASSOC);
+        // var_dump($data);
+        return $data;
+    }
+
+    /**
+     * 单列合计
+     */
+    public function sumColumn($column, $tablename)
+    {
+        $tablename = $tablename ? $tablename : $this->tablename;
+        $sql = "SELECT sum(`$column`) as sumData FROM `$tablename`;";
+        $result = $this->mydb->query($sql);
+        // $data = $result->fetchArray();
+        // var_dump($data['sumData']);exit;
+        if ($data = $result->fetchArray(SQLITE3_ASSOC)) {
+            return $data['sumData'];
+        }
+        return 0;
+    }
+
+    /**
+     * 列表结果集
+     */
+    public function list($where='')
+    {
+        $sql = "select * from $this->tablename $where;";
+        return $this->select($sql);
+    }
+
+    public function listByName($name='', $order = '', $desc = false)
+    {
+        $where = "";
+        if ($name) {
+            $where = " where name like '%$name%'";
+        }
+
+        if ($order) {
+            $where .= " order by $order";
+            if ($desc) {
+                $where .= " desc";
+            } else {
+                $where .= " asc";
+            }
+        }
+        $sql = "select * from $this->tablename $where;";
+        $res = $this->select($sql);
+
+        return $res;
+    }
+
+    /**
+     * save
+     */
+    public function save($data)
+    {
+        $columns = "";
+        $values = "";
+        foreach ($data as $key => $value) {
+            $columns .=  "`" . $key . "`,";
+            $values .=  "'" . $value . "',";
+        }
+        $columns = rtrim($columns, ',');
+        $values = rtrim($values, ',');
+        $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";
+        return $this->exec($sql);
+    }
+    
+    /**
+     * updateById
+     */
+    public function updateById($data)
+    {
+        $id = $data['id'];
+        unset($data['id']);
+        $columns = "";
+        foreach ($data as $key => $value) {
+            $columns .= "`" . $key . "`='" . $value ."',";
+        }
+        $columns = rtrim($columns, ',');
+        $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";
+        return $this->exec($sql);
+    }
+
+    /**
+     * deleteByIds
+     */
+    public function deleteById($id)
+    {
+        $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";
+        if (is_array($id)) {
+            for ($i=0; $i < count($id); $i++) { 
+                $sql .= $id[$i] . ',';
+            }
+            $sql = rtrim($sql, ',');
+            $sql .= ");";
+        } else {
+            $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";
+        }
+        return $this->exec($sql);
+    }
+
+    public function __destruct()
+    {
+        $this->mydb->close();
+    }
+}

+ 118 - 0
daswork/main/View.php

@@ -0,0 +1,118 @@
+<?php
+
+namespace daswork;
+
+class View
+{
+    // 视图实例
+    protected static $instance;
+    // // 模板引擎实例
+    // public $engine;
+    // 模板变量
+    protected $data = [];
+    // 用于静态赋值的模板变量
+    protected static $var = [];
+    // // 视图输出替换
+    // protected $replace = [];
+
+    // /**
+    //  * 构造函数
+    //  * @access public
+    //  * @param array $engine  模板引擎参数
+    //  * @param array $replace  字符串替换参数
+    //  */
+    // public function __construct($engine = [], $replace = [])
+    // {
+    //     //基础替换字符串
+    //     $request = Request::instance();
+    //     $base    = $request->root();
+    //     $root    = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
+    //     if ('' != $root) {
+    //         $root = '/' . ltrim($root, '/');
+    //     }
+    //     $baseReplace = [
+    //         '__ROOT__'   => $root,
+    //         '__URL__'    => $base . '/' . $request->module() . '/' . Loader::parseName($request->controller()),
+    //         '__STATIC__' => $root . '/static',
+    //         '__CSS__'    => $root . '/static/css',
+    //         '__JS__'     => $root . '/static/js',
+    //     ];
+    //     $this->replace = array_merge($baseReplace, (array) $replace);
+    // }
+
+    // /**
+    //  * 初始化视图
+    //  * @access public
+    //  * @param array $engine  模板引擎参数
+    //  * @param array $replace  字符串替换参数
+    //  * @return object
+    //  */
+    // public static function instance($engine = [], $replace = [])
+    // {
+    //     if (is_null(self::$instance)) {
+    //         self::$instance = new self($engine, $replace);
+    //     }
+    //     return self::$instance;
+    // }
+    public static function instance()
+    {
+        if (is_null(self::$instance)) {
+            self::$instance = new self();
+        }
+        return self::$instance;
+    }
+
+
+    /**
+     * 变量名替换
+     * @param $name
+     * @param $value
+     */
+    public function assign($name, $value)
+    {
+        if (is_array($name)) {
+            $this->data = array_merge($this->data, $name);
+        } else {
+            $this->data[$name] = $value;
+        }
+        return $this;
+    }
+
+    /**
+     * 显示视图
+     * @param $file
+     */
+    // public function display($file)
+    // {
+    //     $file = APP.'/views/'.$file;
+    //     if (is_file($file)){
+    //         extract($this->assign);#从数组中将变量导入到当前的符号表
+    //         include $file;
+    //     }
+    // }
+
+    public function fetch($file = "")
+    {
+        // 页面缓存
+        ob_start();
+        ob_implicit_flush(0);
+        if (!empty($this->data)) {
+            extract($this->data);
+        }
+        if ($file) {
+            $namearary = explode(".", $file);
+            $typename = end($namearary);
+            if (!in_array($typename, ['html', 'tpl', 'htm', 'php'])) {
+                $file = $file . '.' . TPL;
+            }
+            $filename = APP_PATH . "/" . $GLOBALS['model'] . "/view/" . strtolower($GLOBALS['ctrl']) . "/" . $file;
+            require($filename);
+        } else {
+            require(APP_PATH . DS . $GLOBALS['model'] . DS . 'view' . DS . strtolower($GLOBALS['ctrl']) . DS . $GLOBALS['action'] . TPL);
+        }
+        // 获取并清空缓存
+        $content = ob_get_clean();
+
+        return $content;
+    }
+}

+ 63 - 0
daswork/main/common/function.php

@@ -0,0 +1,63 @@
+<?php
+/**
+ * 下划线转驼峰
+ * 思路:
+ * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
+ * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
+ */
+function camelize($uncamelized_words, $separator='_')
+{
+    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
+    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
+}
+
+/**
+ * 驼峰命名转下划线命名
+ * 思路:
+ * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
+ */
+function uncamelize($camelCaps, $separator='_')
+{
+    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
+}
+
+/**
+ * 防sql注入字符串转义
+ * @param $content 要转义内容
+ * @return array|string
+ */
+function escapeString($content)
+{
+    $pattern = "/(select[\s])|(insert[\s])|(update[\s])|(delete[\s])|(from[\s])|(where[\s])|(drop[\s])/i";
+    if (is_array($content)) {
+        foreach ($content as $key => $value) {
+            $content[$key] = addslashes(trim($value));
+            if (preg_match($pattern, $content[$key])) {
+                // echo $content[$key];
+                $content[$key] = '';
+            }
+        }
+    } else {
+        $content = addslashes(trim($content));
+        if (preg_match($pattern, $content)) {
+            $content = '';
+        }
+    }
+    return $content;
+}
+
+/**
+ * json 格式输出对象
+ */
+function print_json($data)
+{
+    $res = json_encode($data, JSON_PRETTY_PRINT);
+    if (IS_CLI) {
+        echo $res;
+    } else {
+        // 替换空格和换行符
+        $res = str_replace(' ', '&nbsp;', $res);
+        $res = str_replace("\n", '<br>', $res);
+        echo $res;
+    }
+}

+ 100 - 0
daswork/main/db/Mysql.php

@@ -0,0 +1,100 @@
+<?php
+namespace daswork\db;
+
+use mysqli;
+
+class Mysql
+{
+    //  数据库连接实例
+    private static $instance = [];
+    // 当前数据表名称(含前缀)
+    protected $table = '';
+    // 当前数据表名称(不含前缀)
+    protected $name = '';
+    // 当前数据表主键
+    protected $pk;
+    // 当前数据表前缀
+    protected $prefix = '';
+    // 查询参数
+    protected $options = [];
+
+    /**
+     * 数据库初始化 并取得数据库类实例
+     * @static
+     * @access public
+     * @param mixed         $config 连接配置
+     * @param bool|string   $name 连接标识 true 强制重新连接
+     * @return Connection
+     * @throws Exception
+     */
+    public static function connect($config = [], $name = false) {
+        if (false === $name) {
+            $name = md5(serialize($config));
+        }
+        if (true === $name || !isset(self::$instance[$name])) {
+            if (true === $name) {
+                return self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
+            } else {
+                self::$instance[$name] = self::createConnect($config['host'], $config['username'], $config['passwd'], $config['dbname']);
+            }
+        }
+        return self::$instance[$name];
+    }
+
+    /**
+     * 新建连接
+     */
+    private static function createConnect($host, $username, $passwd, $dbname)
+    {
+        $mysqli = new mysqli($host, $username, $passwd, $dbname);
+        if ($mysqli->connect_error) {
+            throw new \Exception('Connect Error ' . $mysqli->connect_error , $mysqli->connect_errno);
+        }
+        $mysqli->set_charset('utf8');
+        return $mysqli;
+    }
+
+    /**
+     * 指定默认的数据表名(不含前缀)
+     * @access public
+     * @param string $name
+     * @return $this
+     */
+    public function name($name)
+    {
+        $this->name = $name;
+        return $this;
+    }
+
+    /**
+     * 指定默认数据表名(含前缀)
+     * @access public
+     * @param string $table 表名
+     * @return $this
+     */
+    public function setTable($table)
+    {
+        $this->table = $table;
+        return $this;
+    }
+
+    /**
+     * 得到当前或者指定名称的数据表
+     * @access public
+     * @param string $name
+     * @return string
+     */
+    public function getTable($name = '')
+    {
+        if ($name || empty($this->table)) {
+            $name      = $name ?: $this->name;
+            $tableName = $this->prefix;
+            if ($name) {
+                $tableName .= $name;
+            }
+        } else {
+            $tableName = $this->table;
+        }
+        return $tableName;
+    }
+}

+ 41 - 0
daswork/main/response/Json.php

@@ -0,0 +1,41 @@
+<?php
+namespace daswork\response;
+
+use daswork\Response;
+
+class Json extends Response
+{
+    // 输出参数
+    protected $options = [
+        'json_encode_param' => JSON_UNESCAPED_UNICODE,
+    ];
+
+    protected $contentType = 'application/json';
+
+    /**
+     * 处理数据
+     * @access protected
+     * @param mixed $data 要处理的数据
+     * @return mixed
+     * @throws \Exception
+     */
+    protected function output($data)
+    {
+        try {
+            // 返回JSON数据格式到客户端 包含状态信息
+            $data = json_encode($data, $this->options['json_encode_param']);
+
+            if ($data === false) {
+                throw new \InvalidArgumentException(json_last_error_msg());
+            }
+
+            return $data;
+        } catch (\Exception $e) {
+            if ($e->getPrevious()) {
+                throw $e->getPrevious();
+            }
+            throw $e;
+        }
+    }
+
+}

+ 79 - 0
daswork/main/response/View.php

@@ -0,0 +1,79 @@
+<?php
+namespace daswork\response;
+
+use daswork\Config;
+use daswork\Response;
+use daswork\View as ViewTemplate;
+
+class View extends Response
+{
+    // 输出参数
+    protected $options     = [];
+    protected $vars        = [];
+    protected $replace     = [];
+    protected $contentType = 'text/html';
+
+    /**
+     * 处理数据
+     * @access protected
+     * @param mixed $data 要处理的数据
+     * @return mixed
+     */
+    protected function output($data)
+    {
+        // 渲染模板输出
+        return ViewTemplate::instance(Config::get('template'), Config::get('view_replace_str'))
+            ->fetch($data, $this->vars, $this->replace);
+    }
+
+    /**
+     * 获取视图变量
+     * @access public
+     * @param string $name 模板变量
+     * @return mixed
+     */
+    public function getVars($name = null)
+    {
+        if (is_null($name)) {
+            return $this->vars;
+        } else {
+            return isset($this->vars[$name]) ? $this->vars[$name] : null;
+        }
+    }
+
+    /**
+     * 模板变量赋值
+     * @access public
+     * @param mixed $name  变量名
+     * @param mixed $value 变量值
+     * @return $this
+     */
+    public function assign($name, $value = '')
+    {
+        if (is_array($name)) {
+            $this->vars = array_merge($this->vars, $name);
+            return $this;
+        } else {
+            $this->vars[$name] = $value;
+        }
+        return $this;
+    }
+
+    /**
+     * 视图内容替换
+     * @access public
+     * @param string|array $content 被替换内容(支持批量替换)
+     * @param string  $replace    替换内容
+     * @return $this
+     */
+    public function replace($content, $replace = '')
+    {
+        if (is_array($content)) {
+            $this->replace = array_merge($this->replace, $content);
+        } else {
+            $this->replace[$content] = $replace;
+        }
+        return $this;
+    }
+
+}

+ 13 - 0
daswork/service.php

@@ -0,0 +1,13 @@
+<?php
+$uri = urldecode(
+    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
+);
+
+// 这个文件允许我们从内置 PHP web 服务器中模拟 Apache 的 "mod_rewrite" 功能.
+// 使用 Laravel 方法.
+// 而无需在此安装"真正的" web 服务器软件.
+if ($uri !== '/' && file_exists(__DIR__.'../public'.$uri)) {
+    return false;
+}
+
+require_once __DIR__.'/../public/index.php';

+ 24 - 0
daswork/start.php

@@ -0,0 +1,24 @@
+<?php
+namespace daswork;
+
+//定义系统常量
+define('EXT', '.php');
+define('TPL', '.php');
+define("DS", DIRECTORY_SEPARATOR);
+define("DAS_PATH", __DIR__);
+define("CORE_PATH", __DIR__ . DS . "main" . DS);
+// define("TPL",'html');  //模板默认后缀名
+
+// 环境常量
+define('IS_CLI', PHP_SAPI == 'cli' ? true : false);
+define('IS_WIN', strpos(PHP_OS, 'WIN') !== false);
+
+// 载入Loader类
+require CORE_PATH . 'Loader.php';
+// 注册自动加载
+\daswork\Loader::register();
+// 加载公共函数
+require_once CORE_PATH . 'common' . DS . 'function.php';
+
+// 执行应用
+App::run();

BIN
public/favicon.ico


+ 22 - 0
public/index.php

@@ -0,0 +1,22 @@
+<?php
+// +----------------------------------------------------------------------
+// | Daswork simple php formwork
+// +----------------------------------------------------------------------
+// | Copyright (c) none
+// +----------------------------------------------------------------------
+// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
+// +----------------------------------------------------------------------
+// | Time:  2017-10-31 14:36
+// +----------------------------------------------------------------------
+// | Author: huwhois <huwhois@163.com>
+// +----------------------------------------------------------------------
+if(version_compare(PHP_VERSION,'5.3.0','<'))  die('require PHP > 5.3.0 !');
+
+// error_reporting(E_ALL || ~E_NOTICE);
+error_reporting(E_ALL);
+// error_reporting(0);
+
+define( "APP_PATH", __DIR__ . '/../application');
+
+require(__DIR__.'/../daswork/start.php');
+

+ 2 - 0
public/info.php

@@ -0,0 +1,2 @@
+<?php
+phpinfo();

+ 125 - 0
public/model.php

@@ -0,0 +1,125 @@
+package com.baomidou.mybatisplus.extension.service.impl;
+public class ServiceImpl<M extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T>,T> implements com.baomidou.mybatisplus.extension.service.IService {
+  
+  protected org.apache.ibatis.logging.Log log;
+  
+  protected M baseMapper;
+  
+  public ServiceImpl() {
+  }
+  
+  public  M getBaseMapper() {
+    return null;
+  }
+  
+  protected boolean retBool(java.lang.Integer result) {
+    return false;
+  }
+  
+  protected  java.lang.Class<T> currentModelClass() {
+    return null;
+  }
+  
+  protected org.apache.ibatis.session.SqlSession sqlSessionBatch() {
+    return null;
+  }
+  
+  protected void closeSqlSession(org.apache.ibatis.session.SqlSession sqlSession) {
+  }
+  
+  protected java.lang.String sqlStatement(com.baomidou.mybatisplus.core.enums.SqlMethod sqlMethod) {
+    return null;
+  }
+  
+  public  boolean save(T entity) {
+    return false;
+  }
+  
+  public  boolean saveBatch(java.util.Collection<T> entityList, int batchSize) {
+    return false;
+  }
+  
+  public  boolean saveOrUpdate(T entity) {
+    return false;
+  }
+  
+  public  boolean saveOrUpdateBatch(java.util.Collection<T> entityList, int batchSize) {
+    return false;
+  }
+  
+  public boolean removeById(java.io.Serializable id) {
+    return false;
+  }
+  
+  public  boolean removeByMap(java.util.Map<java.lang.String,java.lang.Object> columnMap) {
+    return false;
+  }
+  
+  public  boolean remove(com.baomidou.mybatisplus.core.conditions.Wrapper<T> wrapper) {
+    return false;
+  }
+  
+  public  boolean removeByIds(java.util.Collection<? extends java.io.Serializable> idList) {
+    return false;
+  }
+  
+  public  boolean updateById(T entity) {
+    return false;
+  }
+  
+  public  boolean update(T entity, com.baomidou.mybatisplus.core.conditions.Wrapper<T> updateWrapper) {
+    return false;
+  }
+  
+  public  boolean updateBatchById(java.util.Collection<T> entityList, int batchSize) {
+    return false;
+  }
+  
+  public  T getById(java.io.Serializable id) {
+    return null;
+  }
+  
+  public  java.util.Collection<T> listByIds(java.util.Collection<? extends java.io.Serializable> idList) {
+    return null;
+  }
+  
+  public  java.util.Collection<T> listByMap(java.util.Map<java.lang.String,java.lang.Object> columnMap) {
+    return null;
+  }
+  
+  public  T getOne(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper, boolean throwEx) {
+    return null;
+  }
+  
+  public  java.util.Map<java.lang.String,java.lang.Object> getMap(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return null;
+  }
+  
+  public  int count(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return 0;
+  }
+  
+  public  java.util.List<T> list(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return null;
+  }
+  
+  public  com.baomidou.mybatisplus.core.metadata.IPage<T> page(com.baomidou.mybatisplus.core.metadata.IPage<T> page, com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return null;
+  }
+  
+  public  java.util.List<java.util.Map<java.lang.String,java.lang.Object>> listMaps(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return null;
+  }
+  
+  public <V> java.util.List<V> listObjs(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper, java.util.function.Function<? super java.lang.Object,V> mapper) {
+    return null;
+  }
+  
+  public  com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map<java.lang.String,java.lang.Object>> pageMaps(com.baomidou.mybatisplus.core.metadata.IPage<T> page, com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper) {
+    return null;
+  }
+  
+  public <V> V getObj(com.baomidou.mybatisplus.core.conditions.Wrapper<T> queryWrapper, java.util.function.Function<? super java.lang.Object,V> mapper) {
+    return null;
+  }
+}

+ 5 - 0
start.bat

@@ -0,0 +1,5 @@
+@echo off
+rem �ṩWindows php �����ı�servic���������� (��ͨ�����ߴ��Ϊexe�ļ�)
+
+cd ./public
+php -S localhost:8000 ../daswork/service.php

+ 3 - 0
start.sh

@@ -0,0 +1,3 @@
+#!/bin/bash
+cd ./public
+php -S localhost:8000../daswork/service.php