PHP swoole中http_server的配置与使用方法实例分析(2)
我们在statics目录下创建一个upload.html文件:
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="upload" value=""> <input type="submit" value="提交"> </form> </body> </html>
四、处理路由文件自动加载
<?php
//创建一个http server服务
$server = new swoole_http_server('0.0.0.0', 8888);
$server->set([
//配置项目的目录
'project_path' => __DIR__ . '/src/',
]);
$server->on('WorkerStart', function ($server, $worker_id) {
//注册自动加载函数
spl_autoload_register(function ($class) use($server) {
$class = $server->setting['project_path'] . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($class)) {
include_once $class;
}
});
});
$server->on('request', function ($request, $response) use ($server) {
$pathInfo = explode('/', ltrim($request->server['path_info'], '/'));
//模块/控制器/方法
$module = $pathInfo[0] ?? 'Index';
$controller = $pathInfo[1] ?? 'Index';
$method = $pathInfo[2] ?? 'index';
try {
$class = "\\{$module}\\{$controller}";
$result = (new $class)->{$method}();
$response->end($result);
} catch (\Throwable $e) {
$response->end($e->getMessage());
}
});
//启动服务
$server->start();
我们在目录 src 下创建 test 目录,并创建 test.php 文件
<?php
namespace Test;
class Test
{
public function test()
{
return 'test';
}
}
然后访问 127.0.0.1:8888/test/test/test 就可以看到返回结果了。
通过$request->server['path_info'] 来找到模块,控制器,方法,然后注册我们自已的加载函数,引入文件。实例化类对象,然后调用方法,返回结果。
注意,不要将 spl_autoload_register 放到 onStart 事件回调函数中。
onStart 回调中,仅允许echo、打印Log、修改进程名称。不得执行其他操作。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP网络编程技巧总结》、《php socket用法总结》、《php面向对象程序设计入门教程》、《PHP数据结构与算法教程》及《php程序设计算法总结》
希望本文所述对大家PHP程序设计有所帮助。
