{"id":18027652,"url":"https://github.com/xx19941215/light-framework","last_synced_at":"2025-10-12T18:06:21.952Z","repository":{"id":57085485,"uuid":"124350144","full_name":"xx19941215/light-framework","owner":"xx19941215","description":"A Faster Lightweight PHP Framework","archived":false,"fork":false,"pushed_at":"2018-03-18T09:07:14.000Z","size":118,"stargazers_count":4,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-12T18:06:02.067Z","etag":null,"topics":["ioc","light","mvc","orm","php","phpunit"],"latest_commit_sha":null,"homepage":"http://light-php.xiaoxiao.work","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xx19941215.png","metadata":{"files":{"readme":"README-CN.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-03-08T06:54:14.000Z","updated_at":"2019-12-24T10:07:11.000Z","dependencies_parsed_at":"2022-08-24T22:50:53.129Z","dependency_job_id":null,"html_url":"https://github.com/xx19941215/light-framework","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/xx19941215/light-framework","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xx19941215%2Flight-framework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xx19941215%2Flight-framework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xx19941215%2Flight-framework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xx19941215%2Flight-framework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xx19941215","download_url":"https://codeload.github.com/xx19941215/light-framework/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xx19941215%2Flight-framework/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279012471,"owners_count":26085131,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-12T02:00:06.719Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["ioc","light","mvc","orm","php","phpunit"],"created_at":"2024-10-30T08:12:10.803Z","updated_at":"2025-10-12T18:06:21.918Z","avatar_url":"https://github.com/xx19941215.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/xx19941215/light-framework/releases\"\u003e\u003cimg src=\"https://img.shields.io/github/issues/xx19941215/light-framework.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/xx19941215/light-framework/releases\"\u003e\u003cimg src=\"https://img.shields.io/github/forks/xx19941215/light-framework.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/xx19941215/light-framework/releases\"\u003e\u003cimg src=\"https://img.shields.io/github/stars/xx19941215/light-framework.svg\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/xx19941215/light-framework/releases\"\u003e\u003cimg src=\"https://img.shields.io/badge/php-7.0%2B-blue.svg\"\"\u003e\u003c/a\u003e\n\u003ca href=\"https://opensource.org/licenses/MIT\"\u003e\u003cimg src=\"https://img.shields.io/cocoapods/l/AFNetworking.svg\" alt=\"License\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e \u003ca href=\"./README.md\"\u003eEnglish\u003c/a\u003e　\u003cp\u003e\n\n# 从零开始一步步构建面向生产的PHP框架\n\n需要明确的是，造轮子是学习一门编程语言比较好的方式之一，而不是浪费时间。\n\n那怎样才能构建一个自己的面向生产的PHP框架呢？大致流程如下：\n\n```\n　　　　\n入口文件　----\u003e 载入composer自动加载文件 \n        ----\u003e 注册错误(和异常)处理函数\n        ----\u003e 加载配置文件\n        ----\u003e 请求\n        ----\u003e 路由　\n        ----\u003e（控制器 \u003c----\u003e 数据模型）\n        ----\u003e 视图渲染数据\n```\n\n除此之外我们还需要单元测试、一些辅助脚本等。最终我的框架目录如下：\n\n#  框架目录一览\n\n```\n├── app [PHP应用目录]\n├── bin [构建命令库]\n├── bootstrap [App脚手架]\n│ └── app.php [构建App实例]\n├── config [核心配置目录]\n│ └── .gitignore\n│ └── app.php[app配置]\n│ └── config.php [app基础配置]\n│ └── database.php [数据库配置]\n│ └── i18n.php [国际化配置]\n│ └── session.php [会话配置]\n│ └── site.php [站点配置]\n│ └── swoole.php [swoole配置]\n├── light [Light Framework核心目录]\n├── public [公共资源目录，暴露到万维网]\n│ ├── index.php [后端入口文件]\n│ ├──css [css资源目录]\n│ ├── javascripts [js资源目录]\n├── resources [资源目录]\n│ ├── assets [前端资源目录]\n│       └── sass [sass资源目录]\n│              └── app.scss[入口sass目录]\n│              └── …\n│       └── js [js资源目录]\n│              └── app.js[入口js目录]\n│              └── …\n│ ├── views [PHP视图资源目录]\n│       └── layouts [布局目录]\n│       └── page [page目录]\nstorage [框架其他文件存储目录]\n├── framework [framework缓存目录]\n│             └──cache [缓存目录]\n│                   └── router.php [路由缓存]\n│                   └── config.php [全局配置缓存]\n├── logs [日志目录]\n│             └──error.log [错误日志]\n│             └──light.log [app日志]\n│             └──access.log.gz [访问日志]\n│             └──swoole.log [swoole日志]\ntests [单元测试目录]\n├── demo [模块名称]\n│ └── DemoTest.php [测试演示]\n├── TestCase.php [测试用例]\nvendor [composer目录]\n.env [环境变量文件]\n.gitignore [git忽略文件配置]\nLICENSE [lincese文件]\ncomposer.json [composer配置文件]\ncomposer.lock [composer lock文件]\npackage.json [前端依赖配置文件]\nphpunit.xml [phpunit配置文件]\nREADME-CN.md [中文版readme文件]\nREADME.md [readme文件]\nwebpack.config.js [webpack配置文件]\nyarn.lock [yarn　lock文件]\n\n```\n# 框架生命周期：\n![](http://blog.xiaoxiao.work/wp-content/uploads/2018/02/lifecycle.png)\n# 框架模块说明：\n\n##  入口文件\n\n```PHP\n// 载入框架运行文件\n$app = require __DIR__ . '/../bootstrap/app.php';\n\n//构造Request\n$request = new \\Light\\Http\\Request(\n    $_GET,\n    $_POST,\n    array(),\n    $_COOKIE,\n    $_FILES,\n    $_SERVER\n);\n\n//app处理request\n$response = $app-\u003ehandle($request);\n//发送response\n$response-\u003esend();\n```\n[public/index.php](https://github.com/xx19941215/light/blob/master/public/index.php)\n##  错误和异常模块\n\n脚本运行期间：\n\n- 错误:\n\n通过函数set_error_handler注册用户自定义错误处理方法，但是set_error_handler不能处理以下级别错误，E_ERROR、 E_PARSE、 E_CORE_ERROR、 E_CORE_WARNING、 E_COMPILE_ERROR、 E_COMPILE_WARNING，和在 调用 set_error_handler() 函数所在文件中产生的大多数 E_STRICT。所以我们需要使用register_shutdown_function配合error_get_last获取脚本终止执行的最后错误，目的是对于不同错误级别和致命错误进行自定义处理，例如返回友好的提示的错误信息。\n\n- 异常:\n\n通过函数set_exception_handler注册未捕获异常处理方法，目的捕获未捕获的异常，例如返回友好的提示和异常信息。\n\n\n[light/Concerns/RegistersExceptionHandlers.php](https://github.com/xx19941215/light/blob/master/light/src/Concerns/RegistersExceptionHandlers.php)\n\n##  配置文件模块\n\n加载框架自定义和用户自定义的配置文件。\n```php\nclass Config implements \\ArrayAccess\n{\n    \n}\n```\nConfig类实现了ArrayAccess，可以使用类似访问数组一样的方式访问配置文件。\n\n[light/Config/Config.php](https://github.com/xx19941215/light/blob/master/light/src/Config/Config.php)\n\n##  路由模块\n用法如下\n```\n$this\n    //路由站点\n    -\u003esite('www')\n    //权限设置\n    -\u003eaccess('public')\n    //GET请求\n    -\u003eget(\n    //请求路径\n        '/',\n    //路由别名\n        'index',\n    //分发控制器\n        'Blog\\Index\\Ui\\IndexController@show'\n    );\n```\n在Light中，默认支持多站点路由配置。可以在[`site.php`](https://github.com/xx19941215/light/blob/master/config/site.php)配置。在路由中可以\n使用`site`方法设定当前路由所属的站点。使用`access`方法规定当前路由的接入权限，Light支持`public`、`login`和`admin`以及更加精确的`acl`过滤方式。`get`设定当前路由可以使用GET方法访问，并可以设置访问路径，路由别名和最终的控制器。\n\n[app/blog/post/setting/router/post.php](https://github.com/xx19941215/light/blob/master/app/blog/post/setting/router/post.php)\n\nLight底层的路由基于[`nikic/fast-route`](https://github.com/nikic/FastRoute)实现。\n\n[light/src/Routing/Router.php](https://github.com/xx19941215/light/blob/master/light/src/Routing/Router.php)\n\n## 对象关系映射\n\nObject Relation Mapping, 其主要作用是在编程中，把面向对象的概念跟数据库中表的概念对应起来。举例来说就是，我定义一个对象，那就对应着一张表，这个对象的实例，就对应着表中的一条记录。在框架中，实现了对常用SQL操作的链式封装。后续将会通过操作对象直接完成数据库操作。\n在Light中一个SELECT查询的基本用法\n\n在Repo的子类中\n```php\n$ssb = $this-\u003ecnn-\u003eselect()\n            -\u003efrom('wp_posts')\n            -\u003ewhere('post_status', '=', 'publish')\n            -\u003eandWhere('post_type', '=', 'post')\n            -\u003eorderBy('post_date', 'desc')\n            -\u003elimit(15);\n```\n\n在没有继承Repo的地方(例如View中)，可以通过DB的[`Facade`](https://github.com/xx19941215/light/blob/master/light/src/Support/Facades/DB.php)使用\n\n```php\n$ssb = DB::select()\n            -\u003efrom('wp_posts')\n            -\u003ewhere('post_status', '=', 'publish')\n            -\u003eandWhere('post_type', '=', 'post')\n            -\u003eorderBy('post_date', 'desc')\n            -\u003elimit(15);\n```\n\n返回[`DataSet`](https://github.com/xx19941215/light/blob/master/light/src/Database/DateSet.php)，DataSet实例将对`$ssb`返回的数据做一些简单的处理。\n\n[]()\n\n[app/blog/post/src/repo/ListPostRepo.php](https://github.com/xx19941215/light/blob/master/app/blog/post/src/Repo/ListPostRepo.php)\n\n```php\nreturn $this-\u003edataSet($ssb, Post::class);\n```\n\n在没有继承Repo的地方，可以通过[`collect`](https://github.com/xx19941215/light/blob/master/light/src/Support/functions.php)函数生成DataSet。\n\n输出文章标题列表\n```php\nforeach ($posts-\u003egetItems() as $post) {\n    echo $post-\u003etitle . PHP_EOL;\n}\n```\n##  服务容器模块\n\nLight的核心就是一个服务容器。服务容器提供了整个框架中需要的一系列服务。\n在我们的日常开发中，创建对象的操作随处可见以至于对其十分熟悉的同时又感觉十分繁琐，每次需要对象都需要亲手将其new出来，这是相当糟糕的。但更为严重的是，我们一直倡导的松耦合，少入侵原则，这种情况下变得一无是处。\n\n说到服务容器，不得不提到的就是控制反转，简称为IOC，这是一个常用的设计模式。依赖注入是实现IOC的一种方式。\n\nLight核心实(chao)现(xi)了一个小巧的服务容器。基本attributes和methods如下\n\n```\n- attributes\n    + bindings 抽象和实现之间的映射数组\n    + _instance 容器静态实例\n    # instances 服务实例数组\n    # aliases 服务别名\n    \n- methods\n    + bind 绑定abstract和concrete\n    + getClosure 返回服务Closure便于统一管理\n    + make 生成服务\n    # getConcrete 返回服务的具体实现\n    + build 构建服务对象\n    # getDependencies 从服务容器拿到build时的dependencies\n    # resolveClass 获得给定class的实例\n    # isBuildable 判断当前服务是否可以构建\n    + singleton 单例缓存服务\n    + _setInstance 单例缓存当前容器实例\n    + instance 保存实例\n    + isShared 当前服务实例是否可以共享\n    # dropStaleInstances 删除过期绑定\n    + getAlias 获得服务别名\n    + bound 服务是否已经注册\n    + isAlias 服务是否有别名\n    + _getInstance 获得容器实例\n    + call 获取容器服务，实现控制器调用时的依赖注入\n```\n\n[light/Foundation/App.php](https://github.com/xx19941215/light/blob/master/light/src/Foundation/App.php)\n\n## MVC To MVSC\n\n软件从处理一件事务发展到了要处理许多事务，各事务间有包含、顺序、主次等等的关系，变得越来越复杂。因为数据与逻辑庞大了，所以在Light中，除了传统的MVC三层结构，推荐新增一层Service层来处理繁琐的业务逻辑。\n这个时候，Controller层可以根据设备的不同展示不同的View，但是Service层的业务逻辑得到了复用。\n在Light中，App可以由如下结构组成：\n\n- Model: 作为数据库表的字段的映射存在\n- Repo: 执行Model的crud操作\n- Controller: 处理Service分发的数据和view的展示\n- Service: 处理业务逻辑\n- View: 视图\n\n[Service/FetchPostService.php](https://github.com/xx19941215/light/blob/master/app/blog/post/src/Service/FetchPostService.php)\n\n## View \u0026 Meta \u0026 Trans\nLight的视图层支持布局、组件等方式灵活的组织视图层结构，底层直接使用[`foil`](https://github.com/FoilPHP/Foil)实现，\n你可以在项目的`resource/views`文件夹下放置你的视图文件。\n\nLight在视图层支持每一个页面自定义国际化的`title`、`description`、`keywords`，也支持将其他文本作国际化的输出。\n\n[light/Meta/Meta.php](https://github.com/xx19941215/light/blob/master/light/src/Meta/Meta.php)\n\n## 前端构建\n\nLight使用`webpack`构建`Javascript`，使用`node-sass`编译`scss`文件生产前端样式文件。\n前端资源文件统一放置于`resource/assets`内。\n\n### build步骤\n\n1.依赖安装\n```\nyarn install\n```\n\n2.前端构建脚本\n```\nnpm run build:js\nnpm run build:css\n```\n\n生成的资源文件将会保存在`public`文件夹下的相应目录进行公开访问。\n\n\n## PHPUnit\n基于PHPUnit，Light将会持续完善测试。运行如下的命令即可开始\n```php\n./vendor/bin/phpunit\n```\n\n测试栗子\n\n```php\nclass ConfigTest extends TestCase\n{\n    protected $config;\n    protected $data;\n\n    public function setUp()\n    {\n        $this-\u003econfig = new Config($this-\u003edata = [\n            'foo' =\u003e 'bar',\n            'bar' =\u003e 'baz',\n            'baz' =\u003e 'bat',\n            'null' =\u003e null,\n            'associate' =\u003e [\n                'x' =\u003e 'xxx',\n                'y' =\u003e 'yyy',\n            ],\n            'array' =\u003e [\n                'aaa',\n                'zzz',\n            ],\n            'x' =\u003e [\n                'z' =\u003e 'zoo',\n            ],\n        ]);\n\n        parent::setUp();\n    }\n\n    public function testConstruct()\n    {\n        $this-\u003eassertInstanceOf(Config::class, $this-\u003econfig);\n    }\n}\n```\n\n[light/tests/ConfigTest.php](https://github.com/xx19941215/light/blob/master/light/tests/Config/ConfigTest.php)\n\n\n# 如何使用?\n\n1.通过composer新建项目light-project\n```\ncomposer create-project xx19941215/light-project light-project  \u0026\u0026 cd light-project\n```\n\n2.安装前后端依赖\n```\ncomposer install \u0026\u0026 npm i\n```\n\n3.Nginx server 配置, 请根据你自己项目路径和PHP服务修改相关信息。\n```\nserver {\n    listen  80;\n    #listen [::]:80 ipv6only=on;\n    server_name www.light-project.test\n\t\tstatic.light-projecr.test;\n    \n    #return 301 https://$server_name$request_uri;\n\n    index   index.php index.html;\n    root    /path/to/light-project/public;\n\n    access_log  /path/to/light-project/storage/logs/access.log.gz combined gzip;\n    error_log /path/to/light-project/storage/logs/error.log;\n\n    client_max_body_size 20M;\n\n    gzip  on;\n    gzip_min_length 1k;\n    gzip_buffers 4 16k;\n    gzip_http_version 1.0;\n    gzip_comp_level 6;\n    gzip_types  text/plain application/javascript application/x-javascript text/javascript text/xml text/css;\n    gzip_disable \"MSIE [1-6]\\.\";\n    gzip_vary on;\n\n    location / {\n        try_files $uri $uri/ /index.php?$args;\n    }\n\n    location ~ \\.php(/|$) {\n        try_files $uri = 404;\n        include fastcgi.conf;\n        fastcgi_connect_timeout 60;\n        fastcgi_send_timeout 180;\n        fastcgi_read_timeout 180;\n        fastcgi_buffer_size 128k;\n        fastcgi_buffers 4 256k;\n        fastcgi_busy_buffers_size 256k;\n        fastcgi_temp_file_write_size 256k;\n\n        fastcgi_index   index.php;\n        #fastcgi_pass   unix:/run/php/php7.0-fpm.sock;\n        fastcgi_pass    127.0.0.1:9000;\n\n        location ~ /\\.ht {\n            deny all;\n        }\n    }\n}\n\nserver { \n    listen      80; \n    server_name static.light-project.test; \n \n    index index.html index.htm; \n    root /path/to/light-project/public/static; \n \n    access_log /path/to/light-project/storage/logs/static.access.log.gz combined gzip; \n    error_log /path/to/light-project/storage/logs/static.error.log; \n \n    client_max_body_size 20M; \n \n    location / { \n    } \n \n    location ~* \\.(eot|svg|ttf|woff|woff2)$ { \n        if ($http_origin ~* '^https?://[^/]+\\.light-project\\.test$') { \n            add_header Access-Control-Allow-Origin $http_origin; \n        } \n    } \n \n    location ~ /\\.ht { \n        deny all; \n    } \n}\n```\n\n4.Hosts 配置 \n```\n127.0.0.1 www.light-project.test\n127.0.0.1 static.light-project.test\n```\n\n5.复制.env.example 为.env, 配置 `APP_BASE_HOST` 和相关的数据库配置.\n```\nAPP_DEBUG=true\nAPP_BASE_HOST=light-project.test\nDB_HOST=localhost\nDB_USERNAME=root\nDB_PASSWORD=qwertyuiop\nDB_DATABASE=light\nCACHE_DRIVER=redis\nI18N=false\n```\n\n\n6.确保以下服务正常开启\n```\nredis\nmysql\nphp-fpm\nnginx\n```\n\n\n7.在数据库中增加meta表.\n\n```sql\nCREATE TABLE `meta` (\n  `metaId` varbinary(21) NOT NULL,\n  `key` varchar(20) NOT NULL,\n  `localeKey` varchar(20) NOT NULL,\n  `value` varchar(20) NOT NULL,\n  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  PRIMARY KEY (`metaId`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n```\n\n8.打开浏览器访问 http://www.light-project.test/\n\n# TODO\n\n- Database Migration\n- Security\n- Session\n\n# DONE\n\n- 1.1.3\n    - Console Application","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxx19941215%2Flight-framework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxx19941215%2Flight-framework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxx19941215%2Flight-framework/lists"}