├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── docs ├── integration.md ├── jenkins-pipeline.png └── tars-laravel-http-request.png ├── scripts ├── .gitkeep └── tars2php.sh ├── src ├── App.php ├── Boot.php ├── Commands │ ├── Deploy.php │ └── Tars.php ├── Config.php ├── Controller.php ├── LogHandler.php ├── Registries │ ├── Kong.php │ └── Registry.php ├── Request.php ├── Response.php ├── Route │ ├── TarsRoute.php │ └── TarsRouteFactory.php ├── ServiceProvider.php ├── Tars │ ├── cservant │ │ └── .gitkeep │ ├── impl │ │ └── .gitkeep │ └── servant │ │ └── .gitkeep ├── Util.php ├── config │ └── tars.php ├── controller │ └── LaravelController.php ├── index.php └── services.php └── tars └── tars.proto.php /.gitignore: -------------------------------------------------------------------------------- 1 | composer.phar 2 | /vendor/ 3 | 4 | # Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control 5 | # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file 6 | composer.lock 7 | .idea 8 | .idea/* 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Tars Driver 2 | 3 | ## 中文版 4 | 5 | ### 描述 6 | Tars driver for laravel. 7 | 8 | Laravel集成微服务治理框架Tars 9 | 10 | ### 功能 11 | * 支持服务打包 12 | * 支持Laravel/Lumen原生开发 13 | * 支持TarsConfig 14 | * 支持TarsLog 15 | * 支持网关注册下线 16 | * 支持请求开始(laravel.tars.requesting)、请求结束(laravel.tars.requested)事件 17 | * 支持echo输出内容 18 | * 支持http和tars协议 19 | * 支持zipkin分布式追踪(已移除,可以使用[laravel-zipkin扩展包](https://github.com/luoxiaojun1992/laravel-zipkin)) 20 | 21 | ### 限制 22 | * 受限于框架本身的设计,不支持协程 23 | 24 | ### 环境依赖 25 | 1. Laravel/Lumen5.x 26 | 2. Tars-PHP 27 | 28 | ### 安装 29 | 30 | 1. 创建项目 31 | 32 | 创建Tars项目目录结构(scripts、src、tars),Laravel/Lumen项目放在src目录下 33 | 34 | 2. 安装Laravel Tars包 35 | 36 | 更新Composer依赖 37 | 38 | ```shell 39 | composer require "luoxiaojun1992/laravel-tars:*" 40 | ``` 41 | 42 | 或添加 requirement 到 composer.json 43 | 44 | ```json 45 | { 46 | "require": { 47 | "luoxiaojun1992/laravel-tars": "*" 48 | } 49 | } 50 | ``` 51 | 52 | 添加ServiceProvider,编辑src/bootstrap/app.php 53 | 54 | ```php 55 | $app->register(\Lxj\Laravel\Tars\ServiceProvider::class); 56 | ``` 57 | 58 | 初始化Laravel Tars 59 | 60 | ``` 61 | php artisan vendor:publish --tag=tars 62 | ``` 63 | 64 | 3. 修改配置文件src/config/tars.php文件proto字段,替换appName、serverName、objName 65 | 66 | 4. 如果使用http协议,且需要自动注册到网关(目前仅支持Kong),修改配置文件src/config/tars.php 67 | 68 | ```php 69 | 'registries' => [ 70 | [ 71 | 'type' => 'kong', 72 | 'url' => 'http://kong:8001/upstreams/tars_mysql8/targets', //根据实际情况填写 73 | ] 74 | ] 75 | ``` 76 | 77 | 5. 配置中心(TarsConfig)、日志服务(TarsLog) 78 | 79 | 服务启动时会自动拉取配置,如果需要记录日志,可以使用类似```Log::info('test log');``` 80 | 81 | 如果需要指定TarsLog记录的最低日志级别,修改配置文件src/config/tars.php 82 | 83 | ```php 84 | 'log_level' => \Monolog\Logger::INFO 85 | ``` 86 | 87 | 6. 如果使用http协议,按框架原生方式编写代码 88 | 89 | ```php 90 | $router->get('/test', function () { 91 | \Illuminate\Support\Facades\Log::info('laravel tars test log'); 92 | return 'Laravel Tars Test Success'; 93 | }); 94 | ``` 95 | 96 | 7. 如果使用tars协议 97 | 98 | 在tars目录下编写tars接口描述文件,修改配置文件src/config/tars文件proto字段,新增tarsFiles 99 | 100 | 在scripts目录执行编译脚本生成接口代码 101 | 102 | ```shell 103 | /bin/bash tars2php.sh 104 | ``` 105 | 106 | 在src/app/Tars/impl目录下创建接口实现类,编写业务逻辑代码 107 | 108 | 修改src/config/tars.php文件services字段,替换接口和接口实现命名空间 109 | 110 | 8. 搭建Tars-PHP开发环境 111 | 112 | 如果使用http协议,请参考[TARS-PHP-HTTP服务端与客户端开发](https://tangramor.gitlab.io/tars-docker-guide/3.TARS-PHP-HTTP%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%B8%8E%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%BC%80%E5%8F%91/) 113 | 114 | 如果使用tars协议,请参考[TARS-PHP-TCP服务端与客户端开发](https://tangramor.gitlab.io/tars-docker-guide/2.TARS-PHP-TCP%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%B8%8E%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%BC%80%E5%8F%91/) 115 | 116 | 9. 在Tars-PHP开发环境下打包项目(在src目录下执行```php artisan tars:deploy```) 117 | 118 | 10. 在Tars管理后台发布项目,请参考[TARS-PHP-TCP服务端与客户端开发](https://tangramor.gitlab.io/tars-docker-guide/2.TARS-PHP-TCP%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%B8%8E%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%BC%80%E5%8F%91/)),测试```curl 'http://{ip}:{port}/{api_route}'``` 119 | 120 | ### 使用示例 121 | Laravel请参考 [https://github.com/luoxiaojun1992/laravel-tars-demo](https://github.com/luoxiaojun1992/laravel-tars-demo) 122 | 123 | Lumen请参考 [https://github.com/luoxiaojun1992/lumen-tars-demo](https://github.com/luoxiaojun1992/lumen-tars-demo) 124 | 125 | ### 集成部署 126 | Jenkins Pipeline 配置示例(根据实际情况修改) 127 | 128 | Laravel: 129 | ``` 130 | pipeline { 131 | agent { 132 | node { 133 | label 'phpenv' 134 | } 135 | } 136 | parameters { 137 | string(defaultValue: 'upload_from_jenkins', name: 'TAG_DESC', description: '发布版本描述' ) 138 | string(defaultValue: 'master', name: 'BRANCH_NAME', description: 'git分支,如:develop,master 默认: master') 139 | } 140 | environment { 141 | def JENKINS_HOME = "/root/jenkins" 142 | def PROJECT_ROOT = "$JENKINS_HOME/workspace/laravel-tars-demo" 143 | def APP_NAME = "PHPTest" 144 | def SERVER_NAME = "LaravelTars" 145 | } 146 | stages { 147 | stage('代码拉取与编译'){ 148 | steps { 149 | echo "checkout from git" 150 | git credentialsId:'2', url: 'https://gitee.com/lb002/laravel-tars-demo', branch: "${env.BRANCH_NAME}" 151 | script { 152 | dir("$PROJECT_ROOT/src") { 153 | echo "Composer Install" 154 | sh "composer clear-cache" 155 | sh "composer install -vvv" 156 | sh "cp .env.example .env" 157 | sh "php artisan config:clear" 158 | sh "php artisan config:cache" 159 | } 160 | } 161 | } 162 | } 163 | stage('单元测试') { 164 | steps { 165 | script { 166 | dir("$PROJECT_ROOT/src") { 167 | echo "phpunit 测试" 168 | sh "vendor/bin/phpunit tests/" 169 | echo "valgrind 测试" 170 | } 171 | } 172 | } 173 | } 174 | stage('覆盖率测试') { 175 | steps { 176 | echo "LCOV 覆盖率测试" 177 | } 178 | } 179 | stage('打包与发布') { 180 | steps { 181 | script { 182 | dir("$PROJECT_ROOT/src") { 183 | echo "打包" 184 | sh "php artisan tars:deploy" 185 | echo "发布" 186 | sh "ls *.tar.gz > tmp.log" 187 | echo "上传build包" 188 | def packageDeploy = sh(script: "head -n 1 tmp.log", returnStdout: true).trim() 189 | sh "curl -H 'Host:172.18.0.3:3000' -F 'suse=@./${packageDeploy}' -F 'application=${APP_NAME}' -F 'module_name=${SERVER_NAME}' -F 'comment=${env.TAG_DESC}' http://172.18.0.3:3000/pages/server/api/upload_patch_package > curl.log" 190 | echo "发布build包" 191 | def packageVer = sh(script: "jq '.data.id' curl.log", returnStdout: true).trim() 192 | def postJson = '{"serial":true,"items":[{"server_id":"34","command":"patch_tars","parameters":{"patch_id":' + packageVer + ',"bak_flag":false,"update_text":"${env.TAG_DESC}"}}]}' 193 | echo postJson 194 | sh "curl -H 'Host:172.18.0.3:3000' -H 'Content-Type:application/json' -X POST --data '${postJson}' http://172.18.0.3:3000/pages/server/api/add_task" 195 | } 196 | } 197 | } 198 | } 199 | } 200 | post { 201 | success { 202 | emailext ( 203 | subject: "[jenkins]构建通知:${env.JOB_NAME} 分支: ${env.BRANCH_NAME} - Build# ${env.BUILD_NUMBER} 成功 !", 204 | body: '${SCRIPT, template="groovy-html.template"}', 205 | mimeType: 'text/html', 206 | to: "luoxiaojun1992@sina.cn", 207 | ) 208 | cleanWs() 209 | } 210 | failure { 211 | emailext ( 212 | subject: "[jenkins]构建通知:${env.JOB_NAME} 分支: ${env.BRANCH_NAME} - Build# ${env.BUILD_NUMBER} 失败 !", 213 | body: '${SCRIPT, template="groovy-html.template"}', 214 | mimeType: 'text/html', 215 | to: "luoxiaojun1992@sina.cn", 216 | ) 217 | cleanWs() 218 | } 219 | } 220 | } 221 | ``` 222 | 223 | Lumen: 224 | ``` 225 | pipeline { 226 | agent { 227 | node { 228 | label 'phpenv' 229 | } 230 | } 231 | parameters { 232 | string(defaultValue: 'upload_from_jenkins', name: 'TAG_DESC', description: '发布版本描述' ) 233 | string(defaultValue: 'master', name: 'BRANCH_NAME', description: 'git分支,如:develop,master 默认: master') 234 | } 235 | environment { 236 | def JENKINS_HOME = "/root/jenkins" 237 | def PROJECT_ROOT = "$JENKINS_HOME/workspace/lumen-tars-demo" 238 | def APP_NAME = "PHPTest" 239 | def SERVER_NAME = "LumenTars" 240 | } 241 | stages { 242 | stage('代码拉取与编译'){ 243 | steps { 244 | echo "checkout from git" 245 | git credentialsId:'2', url: 'https://gitee.com/lb002/lumen-tars-demo', branch: "${env.BRANCH_NAME}" 246 | script { 247 | dir("$PROJECT_ROOT/src") { 248 | echo "Composer Install" 249 | sh "composer clear-cache" 250 | sh "composer install -vvv" 251 | sh "cp .env.example .env" 252 | } 253 | } 254 | } 255 | } 256 | stage('单元测试') { 257 | steps { 258 | script { 259 | dir("$PROJECT_ROOT/src") { 260 | echo "phpunit 测试" 261 | sh "vendor/bin/phpunit tests/" 262 | echo "valgrind 测试" 263 | } 264 | } 265 | } 266 | } 267 | stage('覆盖率测试') { 268 | steps { 269 | echo "LCOV 覆盖率测试" 270 | } 271 | } 272 | stage('打包与发布') { 273 | steps { 274 | script { 275 | dir("$PROJECT_ROOT/src") { 276 | echo "打包" 277 | sh "php artisan tars:deploy" 278 | echo "发布" 279 | sh "ls *.tar.gz > tmp.log" 280 | echo "上传build包" 281 | def packageDeploy = sh(script: "head -n 1 tmp.log", returnStdout: true).trim() 282 | sh "curl -H 'Host:172.18.0.3:3000' -F 'suse=@./${packageDeploy}' -F 'application=${APP_NAME}' -F 'module_name=${SERVER_NAME}' -F 'comment=${env.TAG_DESC}' http://172.18.0.3:3000/pages/server/api/upload_patch_package > curl.log" 283 | echo "发布build包" 284 | def packageVer = sh(script: "jq '.data.id' curl.log", returnStdout: true).trim() 285 | def postJson = '{"serial":true,"items":[{"server_id":"33","command":"patch_tars","parameters":{"patch_id":' + packageVer + ',"bak_flag":false,"update_text":"${env.TAG_DESC}"}}]}' 286 | echo postJson 287 | sh "curl -H 'Host:172.18.0.3:3000' -H 'Content-Type:application/json' -X POST --data '${postJson}' http://172.18.0.3:3000/pages/server/api/add_task" 288 | } 289 | } 290 | } 291 | } 292 | } 293 | post { 294 | success { 295 | emailext ( 296 | subject: "[jenkins]构建通知:${env.JOB_NAME} 分支: ${env.BRANCH_NAME} - Build# ${env.BUILD_NUMBER} 成功 !", 297 | body: '${SCRIPT, template="groovy-html.template"}', 298 | mimeType: 'text/html', 299 | to: "luoxiaojun1992@sina.cn", 300 | ) 301 | cleanWs() 302 | } 303 | failure { 304 | emailext ( 305 | subject: "[jenkins]构建通知:${env.JOB_NAME} 分支: ${env.BRANCH_NAME} - Build# ${env.BUILD_NUMBER} 失败 !", 306 | body: '${SCRIPT, template="groovy-html.template"}', 307 | mimeType: 'text/html', 308 | to: "luoxiaojun1992@sina.cn", 309 | ) 310 | cleanWs() 311 | } 312 | } 313 | } 314 | ``` 315 | 316 | Jenkins部署过程 317 | ![Jenkins Pipeline](./docs/jenkins-pipeline.png) 318 | 319 | ### PHP框架集成Tars 320 | [TARS如何集成到PHP框架](./docs/integration.md) 321 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "luoxiaojun1992/laravel-tars", 3 | "description": "Laravel Tars", 4 | "minimum-stability": "stable", 5 | "license": "proprietary", 6 | "authors": [ 7 | { 8 | "name": "author's name", 9 | "email": "email@example.com" 10 | } 11 | ], 12 | "require": { 13 | "illuminate/console": "~5", 14 | "illuminate/support": "~5", 15 | "illuminate/contracts": "~5", 16 | "vlucas/phpdotenv": "~2|~3", 17 | "phptars/tars-server": "~0.6", 18 | "phptars/tars-deploy": "~0.1", 19 | "phptars/tars2php": "~0.1", 20 | "phptars/tars-log": "~0.1", 21 | "laravelista/lumen-vendor-publish": "2.1.0", 22 | "guzzlehttp/guzzle": "^6" 23 | }, 24 | "require-dev": { 25 | "phpunit/phpunit": "*", 26 | "mockery/mockery": "*" 27 | }, 28 | "autoload": { 29 | "psr-4": {"Lxj\\Laravel\\Tars\\": "src/"} 30 | }, 31 | "extra": { 32 | "laravel": { 33 | "providers": [ 34 | "Lxj\\Laravel\\Tars\\ServiceProvider" 35 | ] 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /docs/integration.md: -------------------------------------------------------------------------------- 1 | # TarsPHP与主流框架的结合 2 | 3 | 随着TarsPHP的发布,PHP语言也拥有了包含开发、运维、以及测试的一整套微服务解决方案。但是在实际的应用中, 4 | 还是需要考虑与现有技术栈的融合。如果是新开发的微服务,必须集成路由、ORM、日志等辅助类库。而对于已经存在的服务, 5 | 重新开发的成本也比较高。如果TarsPHP能够实现与主流框架的集成,会大大降低开发成本,帮助PHP开发者更快速地接入Tars 6 | 的基础能力。 7 | 8 | ## TarsPHP集成主流框架的思路 9 | 10 | TarsPHP的服务容器是基于Swoole的能力实现的,并且利用Swoole的Task进程实现主调和监控上报等功能。因此, 11 | TarsPHP与框架的结合的重点就是Swoole和框架的结合,把Swoole的上下文转换成框架的上下文,结合Swoole的http服务 12 | 能力和框架的路由、控制器等功能。除此之外,还需要对接TarsPHP的入口文件、配置下发、日志服务等功能。 13 | 14 | ### 基于TarsPHP组件,包括tars-server、tars-log、tars-monitor、tars-registry等 15 | 16 | 复用TarsPHP的组件,不需要重复实现tars的基础能力,减少开发量,避免重复踩坑,重点关注框架的适配问题。 17 | 18 | Laravel: 19 | ```php 20 | //把TarsPHP入口脚本的参数转换成Laravel的Command参数 21 | $_SERVER['argv'][0] = $argv[0] = __DIR__ .'/artisan'; 22 | $_SERVER['argv'][1] = $argv[1] = 'tars:entry'; 23 | $_SERVER['argv'][2] = $argv[2] = '--cmd=' . $cmd; 24 | $_SERVER['argv'][3] = $argv[3] = '--config_path=' . $config_path; 25 | $_SERVER['argc'] = $argc = count($_SERVER['argv']); 26 | 27 | //执行Laravel的Command 28 | include_once __DIR__ . '/artisan'; 29 | ``` 30 | 31 | ```php 32 | //在Laravel的Command脚本里接收TarsPHP启动脚本传入的cmd和config路径,启动tars-server中的TarsCommand 33 | public function handle() 34 | { 35 | $cmd = $this->option('cmd'); 36 | $cfg = $this->option('config_path'); 37 | 38 | $class = new TarsCommand($cmd, $cfg); 39 | $class->run(); 40 | } 41 | ``` 42 | 43 | Yii2: 44 | ```php 45 | //把TarsPHP入口脚本的参数转换成Yii2的Command参数 46 | $_SERVER['argv'][0] = $argv[0] = 'yii'; 47 | $_SERVER['argv'][1] = $argv[1] = 'tars/entry'; 48 | $_SERVER['argv'][2] = $argv[2] = $cmd; 49 | $_SERVER['argv'][3] = $argv[3] = $config_path; 50 | $_SERVER['argc'] = $argc = count($_SERVER['argv']); 51 | 52 | //执行Yii2的Command 53 | include_once __DIR__ . '/yii'; 54 | ``` 55 | 56 | ```php 57 | //在Yii2的Command脚本里接收TarsPHP启动脚本传入的cmd和config路径,启动tars-server中的TarsCommand 58 | public function actionEntry($cmd, $cfg) 59 | { 60 | $class = new TarsCommand($cmd, $cfg); 61 | $class->run(); 62 | } 63 | ``` 64 | 65 | ### 请求和响应的上下文转换 66 | 67 | ![Tars-Laravel HTTP请求过程](./tars-laravel-http-request.png) 68 | 69 | 在TarsController里,把TarsRequest对象转换成框架的Request对象,然后通过框架的app内核分发 70 | 请求,通过框架的路由最后到达框架的控制器层。控制器返回框架的Response对象,在TarsController中,通过框架 71 | 的Response对象获取HTTP响应头和body,再通过TarsResponse对象将响应头和body发送给客户端。 72 | 73 | 请求上下文的转换: 74 | 75 | Laravel: 76 | ```php 77 | /** 78 | * 根据请求上下文参数生成Laravel的Request对象 79 | * 80 | * @param array $get 81 | * @param array $post 82 | * @param array $cookie 83 | * @param array $files 84 | * @param array $server 85 | * @param string $content 86 | * @return \Illuminate\Http\Request 87 | * @throws \LogicException 88 | */ 89 | protected function createIlluminateRequest($get, $post, $cookie, $files, $server, $content = null) 90 | { 91 | IlluminateRequest::enableHttpMethodParameterOverride(); 92 | 93 | /* 94 | |-------------------------------------------------------------------------- 95 | | Copy from \Symfony\Component\HttpFoundation\Request::createFromGlobals(). 96 | |-------------------------------------------------------------------------- 97 | | 98 | | With the php's bug #66606, the php's built-in web server 99 | | stores the Content-Type and Content-Length header values in 100 | | HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields. 101 | | 102 | */ 103 | 104 | if ('cli-server' === PHP_SAPI) { 105 | if (array_key_exists('HTTP_CONTENT_LENGTH', $server)) { 106 | $server['CONTENT_LENGTH'] = $server['HTTP_CONTENT_LENGTH']; 107 | } 108 | if (array_key_exists('HTTP_CONTENT_TYPE', $server)) { 109 | $server['CONTENT_TYPE'] = $server['HTTP_CONTENT_TYPE']; 110 | } 111 | } 112 | 113 | $request = new SymfonyRequest($get, $post, [], $cookie, $files, $server, $content); 114 | 115 | if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') 116 | && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH')) 117 | ) { 118 | parse_str($request->getContent(), $data); 119 | $request->request = new ParameterBag($data); 120 | } 121 | 122 | $this->illuminateRequest = IlluminateRequest::createFromBase($request); 123 | } 124 | ``` 125 | 126 | Yii2: 127 | ```php 128 | /** 129 | * 继承Yii2的Request,替换原生的方法,通过tarsRequest获取请求上下文 130 | * 131 | * @package Lxj\Yii2\Tars 132 | */ 133 | class Yii2Request extends \yii\web\Request 134 | { 135 | /** 136 | * @var \Tars\core\Request 137 | */ 138 | public $tarsRequest; 139 | 140 | /** 141 | * @param \Tars\core\Request $request 142 | * @return $this 143 | */ 144 | public function setTarsRequest(\Tars\core\Request $request) 145 | { 146 | $this->tarsRequest = $request; 147 | $this->clear(); 148 | return $this; 149 | } 150 | 151 | /** 152 | * @return \Tars\core\Request 153 | */ 154 | public function getTarsRequest() 155 | { 156 | return $this->tarsRequest; 157 | } 158 | 159 | /** 160 | * @inheritdoc 161 | */ 162 | public function getQueryParams() 163 | { 164 | if ($this->_queryParams === null) { 165 | $tarsRequest = $this->getTarsRequest(); 166 | $this->_queryParams = isset($tarsRequest->data['get']) ? $tarsRequest->data['get'] : []; 167 | } 168 | return $this->_queryParams; 169 | } 170 | ... 171 | } 172 | ``` 173 | 174 | 框架的请求分发和路由: 175 | 176 | Laravel: 177 | ```php 178 | /** @var Kernel $kernel */ 179 | $kernel = $application->make(Kernel::class); 180 | $illuminateResponse = $kernel->handle($illuminateRequest); 181 | ``` 182 | 183 | Yii2: 184 | ```php 185 | $application->set('request', $yii2Request); //注入request对象到app容器 186 | $yii2Response = $application->handleRequest($yii2Request); 187 | ``` 188 | 189 | 响应上下文的转换: 190 | 191 | Laravel: 192 | ```php 193 | //通过TarsResponse把Laravel的Response对象中的header和body返回给客户端 194 | 195 | /** 196 | * Sends HTTP headers. 197 | * 198 | * @throws \InvalidArgumentException 199 | */ 200 | protected function sendHeaders() 201 | { 202 | $illuminateResponse = $this->getIlluminateResponse(); 203 | 204 | /* RFC2616 - 14.18 says all Responses need to have a Date */ 205 | if (! $illuminateResponse->headers->has('Date')) { 206 | $illuminateResponse->setDate(\DateTime::createFromFormat('U', time())); 207 | } 208 | 209 | // headers 210 | foreach ($illuminateResponse->headers->allPreserveCaseWithoutCookies() as $name => $values) { 211 | foreach ($values as $value) { 212 | $this->tarsResponse->header($name, $value); 213 | } 214 | } 215 | 216 | // status 217 | $this->tarsResponse->status($illuminateResponse->getStatusCode()); 218 | 219 | // cookies 220 | foreach ($illuminateResponse->headers->getCookies() as $cookie) { 221 | $method = $cookie->isRaw() ? 'rawcookie' : 'cookie'; 222 | 223 | $this->tarsResponse->resource->$method( 224 | $cookie->getName(), $cookie->getValue(), 225 | $cookie->getExpiresTime(), $cookie->getPath(), 226 | $cookie->getDomain(), $cookie->isSecure(), 227 | $cookie->isHttpOnly() 228 | ); 229 | } 230 | } 231 | 232 | /** 233 | * Sends HTTP content. 234 | */ 235 | protected function sendContent() 236 | { 237 | $illuminateResponse = $this->getIlluminateResponse(); 238 | 239 | if ($illuminateResponse instanceof StreamedResponse) { 240 | $illuminateResponse->sendContent(); 241 | } elseif ($illuminateResponse instanceof BinaryFileResponse) { 242 | $this->tarsResponse->resource->sendfile($illuminateResponse->getFile()->getPathname()); 243 | } else { 244 | $this->tarsResponse->resource->end($illuminateResponse->getContent()); 245 | } 246 | } 247 | ``` 248 | 249 | Yii2: 250 | ```php 251 | //通过TarsResponse把Yii2的Response对象中的header和body返回给客户端 252 | 253 | /** 254 | * Sends HTTP headers. 255 | * 256 | * @throws \InvalidArgumentException 257 | */ 258 | protected function sendHeaders() 259 | { 260 | $yii2Response = $this->getYii2Response(); 261 | 262 | /* RFC2616 - 14.18 says all Responses need to have a Date */ 263 | if (! $yii2Response->headers->has('Date')) { 264 | $yii2Response->headers->set('Date', \DateTime::createFromFormat('U', time())); 265 | } 266 | 267 | // headers 268 | foreach ($yii2Response->headers->getIterator() as $name => $values) { 269 | foreach ($values as $value) { 270 | $this->tarsResponse->header($name, $value); 271 | } 272 | } 273 | 274 | // status 275 | $this->tarsResponse->status($yii2Response->getStatusCode()); 276 | } 277 | 278 | /** 279 | * Sends HTTP content. 280 | */ 281 | protected function sendContent() 282 | { 283 | $yii2Response = $this->getYii2Response(); 284 | 285 | $this->tarsResponse->resource->end($yii2Response->content); 286 | } 287 | ``` 288 | 289 | ### 下发Tars-Config配置到框架 290 | 291 | 通过TarsLog组件调用接口获取到远程配置,合并到框架自带的配置项中。在Laravel中,可以直接把配置写入到Config对象 292 | 中。在Yii2中,不支持直接修改Config,可以把远程配置合并到全局的params参数中。 293 | 294 | ```php 295 | //拉取TarsConfig配置项 296 | $communicatorConfig = self::communicatorConfig($deployConfigPath); 297 | $configServant = new \Tars\config\ConfigServant($communicatorConfig); 298 | $configServant->loadConfig($appName, $serverName, 'tars', $configtext); 299 | ``` 300 | 301 | Laravel: 302 | ```php 303 | //合并TarsConfig配置项到Laravel的Config对象 304 | if ($configtext) { 305 | $remoteConfig = json_decode($configtext, true); 306 | foreach ($remoteConfig as $configName => $configValue) { 307 | app('config')->set($configName, array_merge(config($configName) ?: [], $configValue)); 308 | } 309 | } 310 | ``` 311 | 312 | Yii2: 313 | ```php 314 | //合并TarsConfig配置项到Yii2的params数组 315 | if ($configtext) { 316 | $remoteConfig = json_decode($configtext, true); 317 | foreach ($remoteConfig as $configName => $configValue) { 318 | $app = Util::app(); 319 | $localConfig = isset($app->params[$configName]) ? $app->params[$configName] : []; 320 | $app->params[$configName] = array_merge($localConfig, $configValue); 321 | } 322 | } 323 | ``` 324 | 325 | ### 集成Tars-Log到框架的日志组件中 326 | 327 | tars-log组件自带了monolog handler,可以比较方便的集成到使用monolog作为日志引擎的框架,比如Laravel。 328 | 在没有使用monolog作为日志引擎的框架中,可以编写相应的handler来扩展日志输出的方式,比如Yii2 Log Target。 329 | 330 | Laravel: 331 | ```php 332 | //实例化TarsLog自带的Monolog Handler 333 | $communicatorConfig = Config::communicatorConfig($deployConfigPath); 334 | $tarsLogHandler = new \Tars\log\handler\TarsHandler($communicatorConfig, 'tars.tarslog.LogObj', $level); 335 | 336 | //Laravel Monolog实例注册Handler 337 | $logger = app()->make('log'); 338 | $logger->driver()->pushHandler($tarsLogHandler); 339 | ``` 340 | 341 | Yii2: 342 | ```php 343 | //参考TarsLog的Handler实现了Yii2的Log Target 344 | class LogTarget extends Target 345 | { 346 | protected $app = 'Undefined'; 347 | protected $server = 'Undefined'; 348 | protected $dateFormat = '%Y%m%d'; 349 | 350 | private $logServant; 351 | 352 | public $logConf; 353 | public $servantName = 'tars.tarslog.LogObj'; 354 | 355 | public function init() 356 | { 357 | parent::init(); 358 | 359 | $this->logServant = new LogServant($this->logConf, $this->servantName); 360 | 361 | $moduleName = $this->logConf->getModuleName(); 362 | $moduleData = explode('.', $moduleName); 363 | $this->app = $moduleData ? $moduleData[0] : $this->app; 364 | $this->server = isset($moduleData[1]) ? $moduleData[1] : $this->server; 365 | } 366 | 367 | public function export() 368 | { 369 | $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n"; 370 | $this->logServant->logger($this->app, $this->server, '', $this->dateFormat, [$text]); 371 | } 372 | } 373 | 374 | //Yii2注册Log Target 375 | $app->getLog()->getLogger()->dispatcher->targets['tars'] = \Yii::createObject([ 376 | 'class' => LogTarget::class, 377 | 'logConf' => $config, 378 | 'levels' => $level, 379 | 'exportInterval' => $logInterval, 380 | ]); 381 | ``` 382 | 383 | ### 主动释放框架和PHP的全局资源,防止内存泄漏 384 | 385 | ```php 386 | //释放Stat Cache 387 | clearstatcache(); 388 | ``` 389 | 390 | Laravel: 391 | ```php 392 | //在Laravel框架中请求结束需要清除session、cookie等其他数据 393 | if ($illuminateRequest->hasSession()) { 394 | $session = $illuminateRequest->getSession(); 395 | if (is_callable([$session, 'clear'])) { 396 | $session->clear(); // @codeCoverageIgnore 397 | } else { 398 | $session->flush(); 399 | } 400 | } 401 | ... 402 | ``` 403 | 404 | Yii2: 405 | ```php 406 | //在Yii2框架中请求结束需要清除session和缓存的日志数据 407 | if ($app->has('session', true)) { 408 | $app->getSession()->close(); 409 | } 410 | 411 | if($app->state == -1){ 412 | $app->getLog()->logger->flush(true); 413 | } 414 | ``` 415 | 416 | ### 参考主流框架与Swoole结合的开源项目 417 | 418 | 借鉴相对成熟的集成Swoole的开源项目,能够更快地实现上面所说的几点,并且避免一些其他的问题。 419 | 1. Laravool: [https://github.com/garveen/laravoole](https://github.com/garveen/laravoole) 420 | 2. Yii2-Swoole: [https://github.com/tsingsun/yii2-swoole](https://github.com/tsingsun/yii2-swoole) 421 | 3. 更多的项目可以查看Swoole官方文档: [https://wiki.swoole.com/wiki/page/p-framework.html](https://wiki.swoole.com/wiki/page/p-framework.html) 422 | 423 | ## 需要特别注意的几点 424 | 1. 在开发中需要预防内存泄漏。 425 | 2. 非协程框架不能使用协程。 426 | 3. 应用运行在PHP的cli模式下。 427 | 428 | ## 相关项目 429 | 1. TarsPHP: [https://github.com/TarsPHP/TarsPHP](https://github.com/TarsPHP/TarsPHP) 430 | 2. Tars-Laravel: [https://github.com/luoxiaojun1992/laravel-tars](https://github.com/luoxiaojun1992/laravel-tars) 431 | 3. Tars-Yii2: [https://github.com/luoxiaojun1992/yii2-tars](https://github.com/luoxiaojun1992/yii2-tars) 432 | 433 | ## 欢迎品尝和贡献代码 434 | 欢迎品尝TarsPHP、Tars-Laravel和Tars-Yii2,随手点个star,并通过提issue或PR的方式参与其中。 435 | -------------------------------------------------------------------------------- /docs/jenkins-pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/docs/jenkins-pipeline.png -------------------------------------------------------------------------------- /docs/tars-laravel-http-request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/docs/tars-laravel-http-request.png -------------------------------------------------------------------------------- /scripts/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/scripts/.gitkeep -------------------------------------------------------------------------------- /scripts/tars2php.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd ../tars/ 4 | 5 | php ../src/vendor/phptars/tars2php/src/tars2php.php ./tars.proto.php -------------------------------------------------------------------------------- /src/App.php: -------------------------------------------------------------------------------- 1 | make(Kernel::class); 29 | 30 | $request->enableHttpMethodParameterOverride(); 31 | $app->instance('request', $request); 32 | Facade::clearResolvedInstance('request'); 33 | $kernel->bootstrap(); 34 | } 35 | 36 | /** 37 | * @param \Symfony\Component\HttpFoundation\Request $request 38 | * @return mixed 39 | */ 40 | public static function getApp($request) 41 | { 42 | if (!is_null(static::$app)) { 43 | if (!Util::isLumen()) { 44 | static::bootLaravelKernel(static::$app, $request); 45 | } 46 | return static::$app; 47 | } 48 | 49 | static::setTarsDeployCfg(config('tars.deploy_cfg')); 50 | 51 | $oldApp = app(); 52 | 53 | $application = static::createApp(); 54 | static::$app = $application; 55 | 56 | $oldApp->flush(); 57 | Facade::clearResolvedInstances(); 58 | 59 | if (Util::isLumen()) { 60 | Facade::setFacadeApplication($application); 61 | } else { 62 | static::bootLaravelKernel($application, $request); 63 | } 64 | 65 | config(['tars.deploy_cfg' => static::getTarsDeployCfg()]); 66 | Boot::handle(true); 67 | 68 | return $application; 69 | } 70 | 71 | public static function createApp() 72 | { 73 | return include app()->basePath('bootstrap/app.php'); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Boot.php: -------------------------------------------------------------------------------- 1 | $configValue) { 38 | app('config')->set($configName, array_merge(config($configName) ?: [], $configValue)); 39 | } 40 | } 41 | } 42 | 43 | private static function setTarsLog($deployConfigPath, $level = Logger::INFO) 44 | { 45 | $communicatorConfig = Config::communicatorConfig($deployConfigPath); 46 | if (class_exists('Tars\log\handler\TarsHandler')) { 47 | $tarsLogHandlerClass = 'Tars\log\handler\TarsHandler'; 48 | } else { 49 | $tarsLogHandlerClass = LogHandler::class; 50 | } 51 | $tarsLogHandler = new $tarsLogHandlerClass($communicatorConfig, 'tars.tarslog.LogObj', $level); 52 | 53 | $logger = app()->make('log'); 54 | if ($logger instanceof Logger) { 55 | $logger->pushHandler($tarsLogHandler); 56 | } elseif (method_exists($logger, 'driver')) { 57 | $logger->driver()->pushHandler($tarsLogHandler); 58 | } else { 59 | $reflectionObj = new \ReflectionObject($logger); 60 | $monologProp = $reflectionObj->getProperty('monolog'); 61 | $monologProp->setAccessible(true); 62 | $monolog = $monologProp->getValue($logger); 63 | 64 | $monolog->pushHandler($tarsLogHandler); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Commands/Deploy.php: -------------------------------------------------------------------------------- 1 | addOption('cmd', 'cmd', InputOption::VALUE_REQUIRED); 23 | $this->addOption('config_path', 'cfg', InputOption::VALUE_REQUIRED); 24 | } 25 | 26 | public function handle() 27 | { 28 | $cmd = $this->option('cmd'); 29 | $cfg = $this->option('config_path'); 30 | 31 | class_alias(TarsRouteFactory::class, RouteFactory::class); 32 | 33 | list($hostname, $port, $appName, $serverName) = Util::parseTarsConfig($cfg); 34 | 35 | config(['tars.deploy_cfg' => $cfg]); 36 | 37 | Registry::register($hostname, $port); 38 | 39 | $class = new TarsCommand($cmd, $cfg); 40 | $class->run(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Config.php: -------------------------------------------------------------------------------- 1 | loadConfig($appName, $serverName, 'tars', $configtext); 17 | return $configtext; 18 | } 19 | 20 | public static function communicatorConfig($deployConfigPath) 21 | { 22 | if (self::$communicatorConfig && self::$communicatorConfig instanceof CommunicatorConfig) { 23 | return self::$communicatorConfig; 24 | } 25 | 26 | $config = new \Tars\client\CommunicatorConfig(); //这里配置的是tars主控地址 27 | $config->init($deployConfigPath); 28 | $config->setCharsetName("UTF-8"); //字符集 29 | $config->setSocketMode(2); //设置socket model为2 swoole tcp client,1为socket,3为swoole 协程 client 30 | 31 | return self::$communicatorConfig = $config; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Controller.php: -------------------------------------------------------------------------------- 1 | request = $request; 22 | $this->response = $response; 23 | } 24 | public function getResponse() 25 | { 26 | return $this->response; 27 | } 28 | public function getRequest() 29 | { 30 | return $this->request; 31 | } 32 | public function cookie($key, $value = '', $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = false) 33 | { 34 | $this->response->cookie($key, $value, $expire, $path, $domain, $secure, $httponly); 35 | } 36 | // 给客户端发送数据 37 | public function sendRaw($result) 38 | { 39 | $this->response->send($result); 40 | } 41 | public function header($key, $value) 42 | { 43 | $this->response->header($key, $value); 44 | } 45 | public function status($http_status_code) 46 | { 47 | $this->response->status($http_status_code); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/LogHandler.php: -------------------------------------------------------------------------------- 1 | logConf = $config; 29 | $this->logServant = new LogServant($config, $servantName); 30 | 31 | $moduleName = $this->logConf->getModuleName(); 32 | $moduleData = explode('.', $moduleName); 33 | $this->app = $moduleData ? $moduleData[0] : $this->app; 34 | $this->server = isset($moduleData[1]) ? $moduleData[1] : $this->server; 35 | } 36 | 37 | /** 38 | * @return string 39 | */ 40 | public function getApp() 41 | { 42 | return $this->app; 43 | } 44 | 45 | /** 46 | * @param string $app 47 | */ 48 | public function setApp($app) 49 | { 50 | $this->app = $app; 51 | } 52 | 53 | /** 54 | * @return string 55 | */ 56 | public function getServer() 57 | { 58 | return $this->server; 59 | } 60 | 61 | /** 62 | * @param string $server 63 | */ 64 | public function setServer($server) 65 | { 66 | $this->server = $server; 67 | } 68 | 69 | /** 70 | * @return string 71 | */ 72 | public function getDateFormat() 73 | { 74 | return $this->dateFormat; 75 | } 76 | 77 | /** 78 | * @param string $dateFormat 79 | */ 80 | public function setDateFormat($dateFormat) 81 | { 82 | $this->dateFormat = $dateFormat; 83 | } 84 | 85 | 86 | /** 87 | * Writes the record down to the log of the implementing handler 88 | * 89 | * @param array $record 90 | * @return void 91 | * @throws \Exception 92 | */ 93 | protected function write(array $record) 94 | { 95 | $this->logServant->logger($this->app, $this->server, $record['channel'], $this->dateFormat, [$record['formatted']]); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Registries/Kong.php: -------------------------------------------------------------------------------- 1 | [ 13 | 'target' => $hostname . ':' . $port, 14 | 'weight' => 100, 15 | ] 16 | ]); 17 | } 18 | 19 | public static function down($url, $hostname, $port) 20 | { 21 | self::performRequest('POST', $url, [ 22 | 'form_params' => [ 23 | 'target' => $hostname . ':' . $port, 24 | 'weight' => 0, 25 | ] 26 | ]); 27 | } 28 | 29 | private static function performRequest($method, $url, $params) 30 | { 31 | return (new Client())->request($method, $url, $params); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Registries/Registry.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Lxj\Laravel\Tars; 13 | 14 | use Illuminate\Http\Request as IlluminateRequest; 15 | use Tars\core\Request as TarsRequest; 16 | use Symfony\Component\HttpFoundation\ParameterBag; 17 | use Symfony\Component\HttpFoundation\Request as SymfonyRequest; 18 | 19 | class Request 20 | { 21 | /** 22 | * @var \Illuminate\Http\Request 23 | */ 24 | protected $illuminateRequest; 25 | 26 | /** 27 | * Make a request. 28 | * 29 | * @param TarsRequest $tarsRequest 30 | * @return static 31 | */ 32 | public static function make(TarsRequest $tarsRequest) 33 | { 34 | list($get, $post, $cookie, $files, $server, $content) 35 | = self::toIlluminateParameters($tarsRequest); 36 | 37 | return new static($get, $post, $cookie, $files, $server, $content); 38 | } 39 | 40 | /** 41 | * Request constructor. 42 | * 43 | * @param array $get 44 | * @param array $post 45 | * @param array $cookie 46 | * @param array $files 47 | * @param array $server 48 | * @param string $content 49 | * @throws \LogicException 50 | */ 51 | public function __construct(array $get, array $post, array $cookie, array $files, array $server, $content = null) 52 | { 53 | $this->createIlluminateRequest($get, $post, $cookie, $files, $server, $content); 54 | } 55 | 56 | /** 57 | * Create Illuminate Request. 58 | * 59 | * @param array $get 60 | * @param array $post 61 | * @param array $cookie 62 | * @param array $files 63 | * @param array $server 64 | * @param string $content 65 | * @return \Illuminate\Http\Request 66 | * @throws \LogicException 67 | */ 68 | protected function createIlluminateRequest($get, $post, $cookie, $files, $server, $content = null) 69 | { 70 | IlluminateRequest::enableHttpMethodParameterOverride(); 71 | 72 | /* 73 | |-------------------------------------------------------------------------- 74 | | Copy from \Symfony\Component\HttpFoundation\Request::createFromGlobals(). 75 | |-------------------------------------------------------------------------- 76 | | 77 | | With the php's bug #66606, the php's built-in web server 78 | | stores the Content-Type and Content-Length header values in 79 | | HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields. 80 | | 81 | */ 82 | 83 | if ('cli-server' === PHP_SAPI) { 84 | if (array_key_exists('HTTP_CONTENT_LENGTH', $server)) { 85 | $server['CONTENT_LENGTH'] = $server['HTTP_CONTENT_LENGTH']; 86 | } 87 | if (array_key_exists('HTTP_CONTENT_TYPE', $server)) { 88 | $server['CONTENT_TYPE'] = $server['HTTP_CONTENT_TYPE']; 89 | } 90 | } 91 | 92 | $request = new SymfonyRequest($get, $post, [], $cookie, $files, $server, $content); 93 | 94 | if (0 === stripos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') 95 | && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH')) 96 | ) { 97 | parse_str($request->getContent(), $data); 98 | $data = array_merge($post, $data); 99 | $request->request = new ParameterBag($data); 100 | } elseif (0 === stripos($request->headers->get('CONTENT_TYPE'), 'application/json')) { 101 | $data = array_merge($post, json_decode($request->getContent(), true)); 102 | $request->request = new ParameterBag($data); 103 | } 104 | 105 | $this->illuminateRequest = IlluminateRequest::createFromBase($request); 106 | } 107 | 108 | /** 109 | * @return \Illuminate\Http\Request 110 | */ 111 | public function toIlluminate() 112 | { 113 | return $this->getIlluminateRequest(); 114 | } 115 | 116 | /** 117 | * @return \Illuminate\Http\Request 118 | */ 119 | public function getIlluminateRequest() 120 | { 121 | return $this->illuminateRequest; 122 | } 123 | 124 | /** 125 | * Transforms request parameters. 126 | * 127 | * @param TarsRequest $request 128 | * @return array 129 | */ 130 | protected static function toIlluminateParameters(TarsRequest $request) 131 | { 132 | $get = isset($request->data['get']) ? $request->data['get'] : []; 133 | $post = isset($request->data['post']) ? (is_array($request->data['post']) ? $request->data['post'] : []) : []; 134 | $cookie = isset($request->data['cookie']) ? $request->data['cookie'] : []; 135 | $files = isset($request->data['files']) ? $request->data['files'] : []; 136 | $header = isset($request->data['header']) ? $request->data['header'] : []; 137 | $server = isset($request->data['server']) ? $request->data['server'] : []; 138 | $server = self::transformServerParameters($server, $header); 139 | $content = isset($request->data['post']) ? 140 | (is_array($request->data['post']) ? http_build_query($request->data['post']) : $request->data['post']) : 141 | null; 142 | 143 | return [$get, $post, $cookie, $files, $server, $content]; 144 | } 145 | 146 | /** 147 | * Transforms $_SERVER array. 148 | * 149 | * @param array $server 150 | * @param array $header 151 | * @return array 152 | */ 153 | protected static function transformServerParameters(array $server, array $header) 154 | { 155 | $__SERVER = []; 156 | 157 | foreach ($server as $key => $value) { 158 | $key = strtoupper($key); 159 | $__SERVER[$key] = $value; 160 | } 161 | 162 | foreach ($header as $key => $value) { 163 | $key = str_replace('-', '_', $key); 164 | $key = strtoupper($key); 165 | 166 | if (! in_array($key, ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE', 'REMOTE_ADDR', 'SERVER_PORT', 'HTTPS'])) { 167 | $key = 'HTTP_' . $key; 168 | } 169 | 170 | $__SERVER[$key] = $value; 171 | } 172 | 173 | return $__SERVER; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/Response.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * For the full copyright and license information, please view the LICENSE 9 | * file that was distributed with this source code. 10 | */ 11 | 12 | namespace Lxj\Laravel\Tars; 13 | 14 | use Illuminate\Http\Response as IlluminateResponse; 15 | use Tars\core\Response as TarsResponse; 16 | use Symfony\Component\HttpFoundation\BinaryFileResponse; 17 | use Symfony\Component\HttpFoundation\Response as SymfonyResponse; 18 | use Symfony\Component\HttpFoundation\StreamedResponse; 19 | 20 | class Response 21 | { 22 | /** 23 | * @var TarsResponse 24 | */ 25 | protected $tarsResponse; 26 | 27 | /** 28 | * @var \Illuminate\Http\Response 29 | */ 30 | protected $illuminateResponse; 31 | 32 | /** 33 | * Make a response. 34 | * 35 | * @param $illuminateResponse 36 | * @param TarsResponse $tarsResponse 37 | * @return static 38 | */ 39 | public static function make($illuminateResponse, TarsResponse $tarsResponse) 40 | { 41 | return new static($illuminateResponse, $tarsResponse); 42 | } 43 | 44 | /** 45 | * Response constructor. 46 | * 47 | * @param mixed $illuminateResponse 48 | * @param TarsResponse $tarsResponse 49 | */ 50 | public function __construct($illuminateResponse, TarsResponse $tarsResponse) 51 | { 52 | $this->setIlluminateResponse($illuminateResponse); 53 | $this->setTarsResponse($tarsResponse); 54 | } 55 | 56 | /** 57 | * Sends HTTP headers and content. 58 | * 59 | * @throws \InvalidArgumentException 60 | */ 61 | public function send() 62 | { 63 | $this->sendHeaders(); 64 | $this->sendContent(); 65 | } 66 | 67 | /** 68 | * Sends HTTP headers. 69 | * 70 | * @throws \InvalidArgumentException 71 | */ 72 | protected function sendHeaders() 73 | { 74 | $illuminateResponse = $this->getIlluminateResponse(); 75 | 76 | /* RFC2616 - 14.18 says all Responses need to have a Date */ 77 | if (! $illuminateResponse->headers->has('Date')) { 78 | $illuminateResponse->setDate(\DateTime::createFromFormat('U', time())); 79 | } 80 | 81 | // headers 82 | foreach ($illuminateResponse->headers->allPreserveCaseWithoutCookies() as $name => $values) { 83 | foreach ($values as $value) { 84 | $this->tarsResponse->header($name, $value); 85 | } 86 | } 87 | 88 | // status 89 | $this->tarsResponse->status($illuminateResponse->getStatusCode()); 90 | 91 | // cookies 92 | foreach ($illuminateResponse->headers->getCookies() as $cookie) { 93 | $method = $cookie->isRaw() ? 'rawcookie' : 'cookie'; 94 | 95 | $this->tarsResponse->resource->$method( 96 | $cookie->getName(), $cookie->getValue(), 97 | $cookie->getExpiresTime(), $cookie->getPath(), 98 | $cookie->getDomain(), $cookie->isSecure(), 99 | $cookie->isHttpOnly() 100 | ); 101 | } 102 | } 103 | 104 | /** 105 | * Sends HTTP content. 106 | */ 107 | protected function sendContent() 108 | { 109 | $illuminateResponse = $this->getIlluminateResponse(); 110 | 111 | if ($illuminateResponse instanceof StreamedResponse) { 112 | $illuminateResponse->sendContent(); 113 | } elseif ($illuminateResponse instanceof BinaryFileResponse) { 114 | $this->tarsResponse->resource->sendfile($illuminateResponse->getFile()->getPathname()); 115 | } else { 116 | $this->tarsResponse->resource->end($illuminateResponse->getContent()); 117 | } 118 | } 119 | 120 | /** 121 | * @param TarsResponse $tarsResponse 122 | * @return \HuangYi\Http\Server\Response 123 | */ 124 | protected function setTarsResponse(TarsResponse $tarsResponse) 125 | { 126 | $this->tarsResponse = $tarsResponse; 127 | 128 | return $this; 129 | } 130 | 131 | /** 132 | * @return tarsResponse 133 | */ 134 | public function getTarsResponse() 135 | { 136 | return $this->tarsResponse; 137 | } 138 | 139 | /** 140 | * @param mixed illuminateResponse 141 | * @return \HuangYi\Http\Server\Response 142 | */ 143 | protected function setIlluminateResponse($illuminateResponse) 144 | { 145 | if (! $illuminateResponse instanceof SymfonyResponse) { 146 | $content = (string) $illuminateResponse; 147 | $illuminateResponse = new IlluminateResponse($content); 148 | } 149 | 150 | $this->illuminateResponse = $illuminateResponse; 151 | 152 | return $this; 153 | } 154 | 155 | /** 156 | * @return \Illuminate\Http\Response 157 | */ 158 | public function getIlluminateResponse() 159 | { 160 | return $this->illuminateResponse; 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/Route/TarsRoute.php: -------------------------------------------------------------------------------- 1 | toIlluminate(); 32 | 33 | $this->app = $this->app($illuminateRequest); 34 | 35 | list($illuminateRequest, $illuminateResponse) = $this->handle($illuminateRequest); 36 | 37 | $this->terminate($illuminateRequest, $illuminateResponse); 38 | 39 | $this->response($response, $illuminateResponse); 40 | } catch (\Exception $e) { 41 | $response->status(500); 42 | $response->send($e->getMessage() . '|' . $e->getTraceAsString()); 43 | } finally { 44 | if (!is_null($illuminateRequest)) { 45 | $this->clean($illuminateRequest); 46 | } 47 | } 48 | } 49 | 50 | protected function handle($illuminateRequest) 51 | { 52 | if (ob_get_level() > 0) { 53 | ob_end_clean(); 54 | } 55 | ob_start(); 56 | $isObEnd = false; 57 | 58 | event('laravel.tars.requesting', [$illuminateRequest]); 59 | 60 | $application = $this->app; 61 | 62 | if (Util::isLumen()) { 63 | $illuminateResponse = $application->dispatch($illuminateRequest); 64 | } else { 65 | /** @var Kernel $kernel */ 66 | $kernel = $application->make(Kernel::class); 67 | $illuminateResponse = $kernel->handle($illuminateRequest); 68 | } 69 | 70 | if (!($illuminateResponse instanceof BinaryFileResponse)) { 71 | $content = $illuminateResponse->getContent(); 72 | if ((($content === false) || ($content === null)) && ob_get_length() > 0) { 73 | $illuminateResponse->setContent(ob_get_contents()); 74 | ob_end_clean(); 75 | $isObEnd = true; 76 | } 77 | } 78 | 79 | if (!$isObEnd) { 80 | ob_end_flush(); 81 | } 82 | 83 | return [$illuminateRequest, $illuminateResponse]; 84 | } 85 | 86 | protected function terminate($illuminateRequest, $illuminateResponse) 87 | { 88 | $application = $this->app; 89 | 90 | if (Util::isLumen()) { 91 | // Reflections 92 | $reflection = new \ReflectionObject($application); 93 | 94 | $middleware = $reflection->getProperty('middleware'); 95 | $middleware->setAccessible(true); 96 | 97 | $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware'); 98 | $callTerminableMiddleware->setAccessible(true); 99 | 100 | if (count($middleware->getValue($application)) > 0) { 101 | $callTerminableMiddleware->invoke($application, $illuminateResponse); 102 | } 103 | } else { 104 | /** @var Kernel $kernel */ 105 | $kernel = $application->make(Kernel::class); 106 | $kernel->terminate($illuminateRequest, $illuminateResponse); 107 | } 108 | 109 | event('laravel.tars.requested', [$illuminateRequest, $illuminateResponse]); 110 | } 111 | 112 | protected function clean($illuminateRequest) 113 | { 114 | clearstatcache(); 115 | 116 | if ($illuminateRequest->hasSession()) { 117 | $session = $illuminateRequest->getSession(); 118 | if (is_callable([$session, 'clear'])) { 119 | $session->clear(); 120 | } else { 121 | $session->flush(); 122 | } 123 | } 124 | 125 | $application = $this->app; 126 | 127 | if (!is_null($application)) { 128 | if (Util::isLumen()) { 129 | // Clean laravel cookie queue 130 | if ($application->has('cookie')) { 131 | $cookieJar = $application->make('cookie'); 132 | foreach ($cookieJar->getQueuedCookies() as $name => $cookie) { 133 | $cookieJar->unqueue($name); 134 | } 135 | } 136 | 137 | // Reflections 138 | $reflection = new \ReflectionObject($application); 139 | $loadedProviders = $reflection->getProperty('loadedProviders'); 140 | $loadedProviders->setAccessible(true); 141 | $loadedProvidersValue = $loadedProviders->getValue($application); 142 | if (array_key_exists(AuthServiceProvider::class, $loadedProvidersValue)) { 143 | unset($loadedProvidersValue[AuthServiceProvider::class]); 144 | $loadedProviders->setValue($application, $loadedProvidersValue); 145 | $application->register(AuthServiceProvider::class); 146 | unset($loadedProvidersValue[\App\Providers\AuthServiceProvider::class]); 147 | $loadedProviders->setValue($application, $loadedProvidersValue); 148 | $application->register( 149 | \App\Providers\AuthServiceProvider::class 150 | ); 151 | Facade::clearResolvedInstance('auth'); 152 | } 153 | } else { 154 | // Clean laravel cookie queue 155 | if ($application->has(QueueingFactory::class)) { 156 | $cookies = $application->make(QueueingFactory::class); 157 | foreach ($cookies->getQueuedCookies() as $name => $cookie) { 158 | $cookies->unqueue($name); 159 | } 160 | } 161 | 162 | $loadedProviders = $application->getLoadedProviders(); 163 | if (isset($loadedProviders[AuthServiceProvider::class])) { 164 | $application->register(AuthServiceProvider::class, true); 165 | Facade::clearResolvedInstance('auth'); 166 | } 167 | } 168 | } 169 | } 170 | 171 | protected function response($tarsResponse, $illuminateResponse) 172 | { 173 | \Lxj\Laravel\Tars\Response::make($illuminateResponse, $tarsResponse)->send(); 174 | } 175 | 176 | /** 177 | * @param $request 178 | * @return Application 179 | */ 180 | protected function app($request) 181 | { 182 | return App::getApp($request); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/Route/TarsRouteFactory.php: -------------------------------------------------------------------------------- 1 | registerCommands(); 19 | } 20 | 21 | /** 22 | * Register commands. 23 | */ 24 | protected function registerCommands() 25 | { 26 | $commands = [ 27 | Deploy::class, 28 | Tars::class, 29 | ]; 30 | if (Util::isLumen()) { 31 | array_push($commands, VendorPublishCommand::class); 32 | } 33 | $this->commands($commands); 34 | } 35 | 36 | /** 37 | * Perform post-registration booting of services. 38 | * 39 | * @return void 40 | */ 41 | public function boot() 42 | { 43 | if (Util::isLumen()) { 44 | app()->configure('tars'); 45 | } 46 | 47 | $tarsServantDir = base_path('app/Tars/servant'); 48 | $tarsServantImplDir = base_path('app/Tars/impl'); 49 | $tarsCservantDir = base_path('app/Tars/cservant'); 50 | 51 | if (!is_dir($tarsServantDir)) { 52 | mkdir($tarsServantDir, 0755, true); 53 | } 54 | if (!is_dir($tarsServantImplDir)) { 55 | mkdir($tarsServantImplDir, 0755, true); 56 | } 57 | if (!is_dir($tarsCservantDir)) { 58 | mkdir($tarsCservantDir, 0755, true); 59 | } 60 | 61 | $this->publishes([ 62 | __DIR__ . '/index.php' => base_path('index.php'), 63 | __DIR__ . '/Tars/cservant/.gitkeep' => $tarsCservantDir . '/.gitkeep', 64 | __DIR__ . '/services.php' => base_path('services.php'), 65 | __DIR__ . '/../tars/tars.proto.php' => base_path('../tars/tars.proto.php'), 66 | __DIR__ . '/config/tars.php' => base_path('config/tars.php'), 67 | __DIR__ . '/../scripts/tars2php.sh' => base_path('../scripts/tars2php.sh'), 68 | __DIR__ . '/Tars/servant/.gitkeep' => $tarsServantDir . '/.gitkeep', 69 | __DIR__ . '/Tars/impl/.gitkeep' => $tarsServantImplDir . '/.gitkeep', 70 | ], 'tars'); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Tars/cservant/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/src/Tars/cservant/.gitkeep -------------------------------------------------------------------------------- /src/Tars/impl/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/src/Tars/impl/.gitkeep -------------------------------------------------------------------------------- /src/Tars/servant/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luoxiaojun1992/laravel-tars/3357073f2019ff65e9d446425d5625a65d9faae2/src/Tars/servant/.gitkeep -------------------------------------------------------------------------------- /src/Util.php: -------------------------------------------------------------------------------- 1 | \Monolog\Logger::INFO, 5 | 6 | 'registries' => [ 7 | // [ 8 | // 'type' => 'kong', 9 | // 'url' => 'http://kong:8001/upstreams/tars_mysql8/targets', 10 | // ] 11 | ], 12 | 13 | 'services' => [ 14 | 'httpObj' => [ 15 | 'protocolName' => 'http', //http, json, tars or other 16 | 'serverType' => 'http', //http(no_tars default), websocket, tcp(tars default), udp 17 | 'namespaceName' => 'Lxj\Laravel\Tars\\', 18 | 'monitorStoreConf' => [ 19 | //'className' => Tars\monitor\cache\RedisStoreCache::class, 20 | //'config' => [ 21 | // 'host' => '127.0.0.1', 22 | // 'port' => 6379, 23 | // 'password' => ':' 24 | //], 25 | 'className' => Tars\monitor\cache\SwooleTableStoreCache::class, 26 | 'config' => [ 27 | 'size' => 40960 28 | ] 29 | ], 30 | ], 31 | 'tarsObj' => [ 32 | 'protocolName' => 'tars', //http, json, tars or other 33 | 'serverType' => 'tcp', //http(no_tars default), websocket, tcp(tars default), udp 34 | 'home-api' => '\App\Tars\servant\PHPTest\PHPServer\tarsObj\TestTafServiceServant', //根据实际情况替换,遵循PSR-4即可,与tars.proto.php配置一致 35 | 'home-class' => '\App\Tars\impl\TestTafServiceImpl', //根据实际情况替换,遵循PSR-4即可 36 | ], 37 | ], 38 | 39 | 'proto' => [ 40 | 'appName' => 'PHPTest', //根据实际情况替换 41 | 'serverName' => 'PHPServer', //根据实际情况替换 42 | 'objName' => 'tarsObj', //根据实际情况替换 43 | 'withServant' => true, //决定是服务端,还是客户端的自动生成,true为服务端 44 | 'tarsFiles' => array( 45 | //根据实际情况填写 46 | './example.tars', 47 | ), 48 | 'dstPath' => '../src/app/Tars/servant', //可替换,遵循PSR-4规则 49 | 'namespacePrefix' => 'App\Tars\servant', //可替换,遵循PSR-4规则 50 | ], 51 | ]; 52 | -------------------------------------------------------------------------------- /src/controller/LaravelController.php: -------------------------------------------------------------------------------- 1 | handle(); 33 | 34 | $this->terminate($illuminateRequest, $illuminateResponse); 35 | 36 | $this->clean($illuminateRequest); 37 | 38 | $this->response($illuminateResponse); 39 | } catch (\Exception $e) { 40 | $this->status(500); 41 | $this->sendRaw($e->getMessage() . '|' . $e->getTraceAsString()); 42 | } 43 | } 44 | 45 | protected function handle() 46 | { 47 | ob_start(); 48 | $isObEnd = false; 49 | 50 | $illuminateRequest = Request::make($this->getRequest())->toIlluminate(); 51 | 52 | event('laravel.tars.requesting', [$illuminateRequest]); 53 | 54 | $application = $this->app(); 55 | 56 | if (Util::isLumen()) { 57 | $illuminateResponse = $application->dispatch($illuminateRequest); 58 | } else { 59 | /** @var Kernel $kernel */ 60 | $kernel = $application->make(Kernel::class); 61 | $illuminateResponse = $kernel->handle($illuminateRequest); 62 | } 63 | 64 | if (!($illuminateResponse instanceof BinaryFileResponse)) { 65 | $content = $illuminateResponse->getContent(); 66 | if (strlen($content) === 0 && ob_get_length() > 0) { 67 | $illuminateResponse->setContent(ob_get_contents()); 68 | ob_end_clean(); 69 | $isObEnd = true; 70 | } 71 | } 72 | 73 | if (!$isObEnd) { 74 | ob_end_flush(); 75 | } 76 | 77 | return [$illuminateRequest, $illuminateResponse]; 78 | } 79 | 80 | protected function terminate($illuminateRequest, $illuminateResponse) 81 | { 82 | $application = $this->app(); 83 | 84 | if (Util::isLumen()) { 85 | // Reflections 86 | $reflection = new \ReflectionObject($application); 87 | 88 | $middleware = $reflection->getProperty('middleware'); 89 | $middleware->setAccessible(true); 90 | 91 | $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware'); 92 | $callTerminableMiddleware->setAccessible(true); 93 | 94 | if (count($middleware->getValue($application)) > 0) { 95 | $callTerminableMiddleware->invoke($application, $illuminateResponse); 96 | } 97 | } else { 98 | /** @var Kernel $kernel */ 99 | $kernel = $application->make(Kernel::class); 100 | $kernel->terminate($illuminateRequest, $illuminateResponse); 101 | } 102 | 103 | event('laravel.tars.requested', [$illuminateRequest, $illuminateResponse]); 104 | } 105 | 106 | protected function clean($illuminateRequest) 107 | { 108 | if ($illuminateRequest->hasSession()) { 109 | $session = $illuminateRequest->getSession(); 110 | if (is_callable([$session, 'clear'])) { 111 | $session->clear(); // @codeCoverageIgnore 112 | } else { 113 | $session->flush(); 114 | } 115 | } 116 | 117 | $application = $this->app(); 118 | 119 | if (Util::isLumen()) { 120 | // Clean laravel cookie queue 121 | if ($application->has('cookie')) { 122 | $cookieJar = $application->make('cookie'); 123 | foreach ($cookieJar->getQueuedCookies() as $name => $cookie) { 124 | $cookieJar->unqueue($name); 125 | } 126 | } 127 | 128 | // Reflections 129 | $reflection = new \ReflectionObject($application); 130 | $loadedProviders = $reflection->getProperty('loadedProviders'); 131 | $loadedProviders->setAccessible(true); 132 | $loadedProvidersValue = $loadedProviders->getValue($application); 133 | if (array_key_exists(AuthServiceProvider::class, $loadedProvidersValue)) { 134 | unset($loadedProvidersValue[AuthServiceProvider::class]); 135 | $loadedProviders->setValue($application, $loadedProvidersValue); 136 | $application->register(AuthServiceProvider::class); 137 | Facade::clearResolvedInstance('auth'); 138 | } 139 | } else { 140 | // Clean laravel cookie queue 141 | $cookies = $application->make(QueueingFactory::class); 142 | foreach ($cookies->getQueuedCookies() as $name => $cookie) { 143 | $cookies->unqueue($name); 144 | } 145 | 146 | $loadedProviders = $application->getLoadedProviders(); 147 | if (isset($loadedProviders[AuthServiceProvider::class])) { 148 | $application->register(AuthServiceProvider::class, true); 149 | Facade::clearResolvedInstance('auth'); 150 | } 151 | } 152 | } 153 | 154 | protected function response($illuminateResponse) 155 | { 156 | Response::make($illuminateResponse, $this->getResponse())->send(); 157 | } 158 | 159 | protected function app() 160 | { 161 | if (self::$app) { 162 | return self::$app; 163 | } 164 | return self::$app = $this->createApp(); 165 | } 166 | 167 | protected function createApp() 168 | { 169 | return include app()->basePath('bootstrap/app.php'); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/index.php: -------------------------------------------------------------------------------- 1 | load(); 15 | } else { 16 | (new Dotenv\Dotenv(__DIR__ . '/'))->load(); 17 | } 18 | 19 | list($hostname, $port, $appName, $serverName) = \Lxj\Laravel\Tars\Util::parseTarsConfig($config_path); 20 | 21 | $localConfig = include_once __DIR__ . '/config/tars.php'; 22 | 23 | \Lxj\Laravel\Tars\Registries\Registry::down($hostname, $port, $localConfig); 24 | 25 | $class = new \Tars\cmd\Command($cmd, $config_path); 26 | $class->run(); 27 | } else { 28 | $argv = $argv ?? []; 29 | $_SERVER['argv'][0] = $argv[0] = __DIR__ .'/artisan'; 30 | $_SERVER['argv'][1] = $argv[1] = 'tars:entry'; 31 | $_SERVER['argv'][2] = $argv[2] = '--cmd=' . $cmd; 32 | $_SERVER['argv'][3] = $argv[3] = '--config_path=' . $config_path; 33 | $_SERVER['argc'] = $argc = count($_SERVER['argv']); 34 | 35 | include_once __DIR__ . '/artisan'; 36 | } 37 | -------------------------------------------------------------------------------- /src/services.php: -------------------------------------------------------------------------------- 1 |