{"id":18083505,"url":"https://github.com/leizongmin/leiphp","last_synced_at":"2026-03-07T03:31:11.791Z","repository":{"id":4398348,"uuid":"5535503","full_name":"leizongmin/leiphp","owner":"leizongmin","description":"轻量级的 PHP MVC 框架 Lightweight MVC framework for simplistic PHP apps","archived":false,"fork":false,"pushed_at":"2020-01-14T16:39:56.000Z","size":85,"stargazers_count":30,"open_issues_count":1,"forks_count":10,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-12T17:14:24.426Z","etag":null,"topics":["composer-package","framework","leiphp-php","mvc","php"],"latest_commit_sha":null,"homepage":"http://morning.work","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/leizongmin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"MIT-License","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-08-24T03:22:09.000Z","updated_at":"2022-07-26T09:31:30.000Z","dependencies_parsed_at":"2022-09-02T16:38:05.647Z","dependency_job_id":null,"html_url":"https://github.com/leizongmin/leiphp","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/leizongmin/leiphp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leizongmin%2Fleiphp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leizongmin%2Fleiphp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leizongmin%2Fleiphp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leizongmin%2Fleiphp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/leizongmin","download_url":"https://codeload.github.com/leizongmin/leiphp/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leizongmin%2Fleiphp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30206563,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T03:24:23.086Z","status":"ssl_error","status_checked_at":"2026-03-07T03:23:11.444Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["composer-package","framework","leiphp-php","mvc","php"],"created_at":"2024-10-31T14:08:20.335Z","updated_at":"2026-03-07T03:31:11.772Z","avatar_url":"https://github.com/leizongmin.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"![version](https://img.shields.io/packagist/v/leizongmin/leiphp.svg)\n![php](https://img.shields.io/packagist/php-v/leizongmin/leiphp.svg)\n![license](https://img.shields.io/packagist/l/leizongmin/leiphp.svg)\n![downloads](https://img.shields.io/packagist/dt/leizongmin/leiphp.svg)\n\n# LeiPHP 轻量级的 PHP MVC 框架\n\nLightweight MVC framework for simplistic PHP apps.\n\nLeiPHP is contained in one single PHP file. It works based on a config file and is perfect for small to medium PHP-powered projects.\n\nFeatures:\n\n* Supports database interaction\n* Support for file uploads\n* Debugging tools\n* File dependency management\n* Template engine\n* REST-based routing\n* Easy to initialize\n\n此框架仅有一个文件，其中包含了MySQL数据库、上传文件、调试信息、导入依赖文件、模板和REST路由等一系列常用操作。API接口简单，学习成本低，开箱即用，适合用来快速写一些对性能要求不高的程序。\n\n## 项目文件结构\n\n```text\n.\n├── action          路由处理程序目录\n├── global.inc.php  项目公共文件文件\n├── index.php       项目入口文件\n├── lib             公共代码目录\n├── public          静态资源文件目录\n└── template        模板目录\n```\n\n## 安装\n\n* 直接下载`lei.php`文件：`wget https://raw.githubusercontent.com/leizongmin/leiphp/master/lei.php`\n* 通过`composer`安装：`composer require leizongmin/leiphp`\n\n## 初始化\n\n首先新建一个`global.inc.php`文件，所有程序通过加载该文件来进行配置及初始化：\n\n```php\n\u003c?php\n/**\n * 公共文件\n */\n\n// 载入LeiPHP\nrequire('lei.php');\n\n// 当前应用的根目录\nAPP::set('ROOT', dirname(__FILE__ ).'/');\n// 模板根目录\nAPP::set('TEMPLATE_ROOT', APP::get('ROOT').'template/');\n\n// 输出调试信息，生成环境请去掉这行或设置为false\nAPP::set('DEBUG', true);\n\n// MYSQL数据库配置，如果不定义数据库配置，则不自动连接数据库\nAPP::set('MYSQL_SERVER', 'localhost:3306');  // 服务器，默认为 localhost:3306，使用长连接在地址前加 p:，如：p:localhost:3306\nAPP::set('MYSQL_USER',   'root');            // 用户名，默认为 root\nAPP::set('MYSQL_PASSWD', '123456');          // 密码，默认为空\nAPP::set('MYSQL_DBNAME', 'test');            // 数据库名，默认为空\nAPP::set('MYSQL_PERMANENT', false);          // 使用使用永久连接，默认false\n\n// 初始化\nAPP::init();\n?\u003e\n```\n\n如果通过`composer`安装，则载入路径应改为：\n\n```php\nrequire('vendor/leizongmin/leiphp/lei.php');\n```\n\n在所有php程序中，均可载入`global.inc.php`文件唉实现初始化LeiPHP：\n\n```php\n\u003c?php\nrequire('global.inc.php');\n// ...\n?\u003e\n```\n\n## REST路由\n\nLeiPHP可以根据不同的请求方法来调用相应的处理函数完成请求，比如：\n\n```php\n\u003c?php\nrequire('global.inc.php');\n\n// 这里是公共部分的代码，所有请求方法都会执行下面的代码\necho '所有请求方法都会执行这里的代码';\n\n// 定义处理GET请求的代码\nfunction method_get () {\n  echo 'GET请求方法的处理代码';\n}\n\n// 定义处理POST请求的代码\nfunction method_post () {\n  echo 'POST请求方法的处理代码';\n}\n\n// 定义处理DELETE请求的代码\nfunction method_delete () {\n  echo 'DELETE请求方法的处理代码';\n}\n\n// 定义处理PUT请求的代码\nfunction method_put () {\n  echo 'PUT请求方法的处理代码';\n}\n\n?\u003e\n```\n\n## 模板渲染\n\nLeiPHP中提供了一个静态类 __TPL__ 来渲染HTML模板：\n\n```php\n// 设置模板变量\nTPL::set_val('模板变量', '值');\n// 渲染模板\nTPL::render('模板名');\n```\n\n模板文件存放在`template`目录内，比如要渲染`template/index.html`：\n\n```php\nTPL::render('index');\n```\n\n模板文件中通过`$locals`变量来获取模板数据：\n\n```php\n\u003c?= $locals['模板变量'] ?\u003e\n\u003c?php foreach ($item as $list): ?\u003e\n  \u003c?= $item ?\u003e\n\u003c?php endforeach; ?\u003e\n```\n\n以下为模板渲染相关的方法：\n\n* `TPL::get($name, $locals)` 载入模板文件，若不指定后缀名，会自动加上`.html`，以常量`APP_TPL_ROOT`定义的模板目录作为根目录，模板文件实际上为php程序文件，第二个参数为模板中可用的变量，在模板中通过`$locals`来读取（若无命名冲突也可以直接使用键名），返回渲染后的内容；\n* `TPL::set_val($name, $value)` 设置模板变量；\n* `TPL::get_val($name)` 取模板变量值；\n* `TPL::render($name, $locals, $layout = '')` 自动为`$locals`加上用`APP::set_val()`设置的变量，并渲染模板。如果指定了视图模板`$layout`，则需要在视图模板中通过`$body`变量来获取模板内容；\n\n## 操作MySQL数据库\n\nLeiPHP中提供了一个静态类 __SQL__ 来操作MySQL数据库（基于 __mysqli__ 实现）：\n\n* `SQL::connect($server = 'localhost:3306', $username = 'root', $password = '',$database = '');`连接到数据库，当配置了数据库连接时，leiapp会自动执行此方法来连接到数据库，若你的程序中已经通过`mysqli_connect`来创建了一个数据库连接，可以不用再执行此方法连接数据库（如果要使用永久连接来提高性能，可以在`$server`前加字符串`p:`，如：`p:localhost:3306`）；\n* `SQL::find_all($sql)` 查询SQL，并返回数组格式的结果，失败返回`FALSE`；\n* `SQL::find_one($sql)` 查询SQL，仅返回第一条结果，失败返回`FALSE`；\n* `SQL::update($sql)` 查询SQL，返回受影响的记录数，一般用于执行插入或更新操作；\n* `SQL::id()` 或 `SQL::lastId()` 返回最后插入的一条记录的ID；\n* `SQL::errno()` 返回最后执行的一条SQL语句的出错号；\n* `SQL::errmsg()` 返回最后执行的一条SQL语句的出错信息；\n* `SQL::escape($str)` 返回安全的SQL字符串；\n\n更简便的数据库操作：\n\n* `SQL::find_all($table, $where)` 查询所有记录，其中$table是表名，$where是一个条件数组，如：`array('id' =\u003e 1)`；\n* `SQL::find_one($table, $where)` 查询一条记录；\n* `SQL::update($table, $where, $update)` 更新记录并返回受影响的记录数，其中$update是要更新的数据数组，如：`array('name' =\u003e 'haha')`；\n* `SQL::insert($table, $data)` 插入一条记录并返回其ID，其中$data是一个数组，如：`array('name' =\u003e 'haha', 'age' =\u003e 20)`；\n* `SQL::delete($table, $where)` 删除记录；\n\n条件格式：\n\n* 普通：`array('a' =\u003e 1, 'b' =\u003e 2)` 相当于 `a=1 AND b=2`；\n* 指定连接操作符：`array('link' =\u003e 'OR', 'a' =\u003e 1, 'b' =\u003e 2)` 相当于 `a=1 OR b=2`；\n* 指定比较操作符：`array('a' =\u003e array('\u003e' =\u003e 2))` 相当于 `a\u003e2`；\n* 同一个字段多个条件：`array('a' =\u003e array('\u003e' =\u003e 2, '\u003c' =\u003e 5))` 相当于`(a\u003e2 AND a \u003c 5)`；\n* 指定多个条件的连接操作符：`array('a' =\u003e array('link' =\u003e 'OR', '\u003e' =\u003e 2, '\u003c' =\u003e 5))`相当于 `(a\u003e2 OR a \u003c 5)`；\n\n## 上传文件操作\n\nLeiPHP中提供了一个静态类 __UPLOAD__ 来操作上传文件：\n\n* `UPLOAD::get($filename)` 返回指定名称的上传文件信息，该名称为`\u003cform\u003e`表单中的`\u003cinput type=\"file\"\u003e`中的**name**值，该返回值为一个数组，包含以下项： __name__（名称）， __type__ （MIME类型）， __size__ （大小），__tmp_name__ （临时文件名）；\n* `UPLOAD::move($file, $target)` 移动上传的文件到指定位置，第一个参数为`UPLOAD::get($filename)`的返回值，第二个参数为目标文件名；\n\n## 调试信息操作\n\nLeiPHP中提供了一个静态类 __DEBUG__ 来操作调试信息，当定义了常量`APP_DEBUG`时，\n会在页面底部输出调试信息：\n\n* `DEBUG::put($msg = '', $title = '')` 输出调试信息；\n* `DEBUG::get()` 取调试信息；\n* `DEBUG::clear()` 清除所有调试信息；\n\n## 应用相关操作\n\nLeiPHP中提供了一个静态类 __APP__ 来进行应用相关的操作，及一些公共函数：\n\n* `APP::set($name, $value)` 设置\n* `APP::get($name)` 获取设置值\n* `APP::is_set($name)` 检查是否有指定设置项\n* `APP::encrypt_password ($password)` 加密密码，返回一个加盐处理后的MD5字符串，如：`FF:15855D447208A6AB4BD2CC88D4B91732:83`；\n* `APP::validate_password ($password, $encrypted)` 验证密码，第一个参数为待验证的密码，第二个参数为`APP::encrypt_password ($password)`返回的字符串，返回`TRUE`或`FALSE`；\n* `APP::dump($var)` 打印变量结构，一般用于调试；\n* `APP::show_error($msg)` 显示出错信息；\n* `APP::load($filename)` 载入依赖的php文件，若不指定后缀名，会自动加上`.php`，默认以当前php文件为根目录，若文件名以`/`开头，则以常量`APP_ROOT`定义的应用目录作为根目录；几种用途：\n  * 载入依赖文件：`APP::load('xxx.php')`；\n  * 使用php文件存储数据，将其读取出来：`$data = APP::load('data.php')`，php文件内容：`\u003c?php return [1,2]; ?\u003e`；\n  * 使用json文件存储数据，将其读取出来：`$data = APP::load('data.json')`，json文件内容：`[1,2]`；\n* `APP::send_json($data)` 返回JSON格式数据；\n* `APP::send_json_error($msg, $data = array())` 返回JSON格式的出错信息：`{\"error\":\"msg\"}`；\n* `APP::auth_encode($string, $key, $expirey)` 加密账户验证信息，可指定过期时间；\n* `APP::auth_decode($string, $key)` 加密账户验证信息；\n* `APP::init()` 初始化LeiPHP；\n* `APP::end()` 提前退出；\n\n## 自动路由\n\nLeiPHP中提供了一个静态类 __ROUTER__ 来进行路由相关的操作：\n\n* `ROUTER::register($path, $function, $is_preg = false)` 注册中间件，其中`$path`为路径前缀，`$function`为要执行的函数，如果`$is_preg`为`true`表示`$path`是一个正则表达式;\n* `ROUTER::run($dir, $path)` 执行自动路由。其中`$dir`是要自动加载的PHP文件所在的目录，以应用目录`APP_ROOT`中定义的目录为根目录，默认为`action`目录，`$path`是当前请求的路径，默认为`$_GET['__path__']`;\n\n### 示例\n\n新建应用统一入口文件：`index.php`：\n\n```php\n\u003c?php\nrequire('global.inc.php');\nROUTER::run('action', @$_GET['__path__']);\n?\u003e\n```\n\n新建首页处理程序：`action/index.php`：\n\n```php\nfunction method_get() {\n  echo 'hello, world';\n}\n```\n\n需要配置服务器的URL Rewrite，比如将 `/app/(.*)` 的所有请求转到`/app/index.php?__path__=$1`\n\n### 使用PATH_INFO\n\n```php\n\u003c?php\nrequire('global.inc.php');\nROUTER::run('action', @$_SERVER['PATH_INFO']);\n?\u003e\n```\n\n通过`/index.php/xxxx`访问。\n\n### Apache的配置示例\n\n```text\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^app/(.*)$ /app/index.php?%{QUERY_STRING}\u0026__path__=$1 [L]\n```\n\n### Nginx的配置示例\n\n```nginx\nif (!-e $request_filename) {\n  rewrite \"^/app/(.*)\" \"/app/index.php?%{QUERY_STRING}\u0026__path__=$1\" last;\n}\n```\n\n### SAE的配置示例\n\n```yaml\nhandle:\n - rewrite: if(!is_dir() \u0026\u0026 !is_file() \u0026\u0026 path~\"^app/(.*)\") goto \"app/index.php?%{QUERY_STRING}\u0026__path__=$1\"\n```\n\n当请求 `/app/my/action` 时，会自动执行文件 `/action/my/action.php`\n\n如请求 `/app/my/action/` ，则自动执行文件 `/action/my/action/index.php`\n\n## License\n\n基于MIT协议发布。\n\n```text\nCopyright (c) 2012-2019 Zongmin Lei \u003cleizongmin@gmail.com\u003e\nhttp://ucdok.com\n\nThe MIT License\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleizongmin%2Fleiphp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleizongmin%2Fleiphp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleizongmin%2Fleiphp/lists"}