PHP code example of kode / http
1. Go to this page and download the library: Download kode/http library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kode / http example snippets
ode\Http\App;
use Kode\Http\Request;
use Kode\Http\Response;
$app = App::create();
$app->get('/api/hello', function() {
$name = Request::get('name', 'World');
return Response::success(['greeting' => "你好,{$name}!"]);
});
$app->serve(8080);
// 参数获取(自动从当前请求获取)
Request::get('name'); // GET 参数
Request::post('name'); // POST 参数
Request::json('name'); // JSON body 参数
Request::header('Authorization'); // 请求头
Request::cookie('session_id'); // Cookie
// 字段选择(借鉴 Laravel)
Request::only('name', 'email'); // 仅获取指定字段
Request::except('password', 'token'); // 排除指定字段
// 判断存在(借鉴 ThinkPHP)
Request::has('name'); // 参数是否存在
Request::missing('token'); // 参数是否缺失
// 获取所有参数
Request::all(); // 合并 query + body
// 请求信息
Request::ip(); // 客户端 IP
Request::method(); // 请求方法
Request::path(); // 请求路径
Request::isAjax(); // 是否 AJAX 请求
Request::isJson(); // 是否 JSON 请求
Request::isMobile(); // 是否移动端
Request::isGet(); // 是否 GET 请求
Request::isPost(); // 是否 POST 请求
// 其他
Request::userAgent(); // User-Agent
Request::referer(); // 来源页面
Request::language(); // Accept-Language
Request::time(); // 请求时间戳
Request::file('avatar'); // 上传文件
Request::server('REQUEST_TIME'); // 服务器变量
// JSON 响应(直接 return,无需 ->send())
return Response::json(['data' => 'value']);
return Response::json(['data' => 'value'], 1); // 带业务码
// 业务响应(借鉴 Laravel)
return Response::success(['id' => 1], '操作成功');
return Response::fail('用户名或密码错误', 'E1001');
// HTTP 错误
return Response::error(404, 'Not Found');
return Response::error(500, 'Internal Server Error', 'E1500');
// 其他响应类型
return Response::text('Hello World');
return Response::html('<h1>Title</h1>');
return Response::xml('<root></root>');
return Response::empty(); // 204 空响应
return Response::redirect('/login'); // 302 重定向
return Response::download('/path/file.pdf');
// 链式调用(cookie / CORS / 安全头等都是 PSR-7 上的方法)
return Response::success(['data' => $data])
->status(201)
->header('X-Custom', 'value')
->withCors()
->withCache(3600)
->withSecurity()
->cookie('token', $jwt, httpOnly: true);
use Kode\Http\App;
use Kode\Http\Request;
use Kode\Http\Response;
$app = App::create(debug: true);
// 添加中间件
$app->use(function($req, $next) {
$start = microtime(true);
$response = $next->handle($req);
return $response->withHeader('X-Execution-Time', sprintf('%.2fms', (microtime(true) - $start) * 1000));
});
// 路由注册
$app->get('/api/users', function() {
return Response::success(['users' => [
['id' => 1, 'name' => '张三'],
['id' => 2, 'name' => '李四'],
]]);
});
$app->post('/api/users', function() {
$name = Request::json('name');
$email = Request::json('email');
if (empty($name)) {
return Response::fail('用户名不能为空', 'E1001', 400);
}
return Response::success(['id' => rand(1000, 9999)], '创建成功');
});
// 路由参数
$app->get('/api/users/{id}', function() {
$id = Request::param('id'); // 路由参数(等价 Request::attr('id'))
return Response::success(['id' => $id]);
});
$app->delete('/api/users/{id}', function() {
return Response::success(null, '删除成功');
});
// 路由组
$app->group('/api/v1', function($api) {
$api->get('/status', fn() => Response::success(['status' => 'ok']));
$api->post('/action', fn() => Response::success());
});
// HTTP 方法
$app->patch('/api/users/{id}', fn() => Response::success());
$app->options('/api/users', fn() => Response::empty());
$app->any('/api/health', fn() => Response::success());
// 运行
$app->serve(8080);
use Kode\Http\Kode;
use Kode\Http\Support\ServiceFacade;
Kode::register('cache', new Cache());
Kode::enableFacades(); // 将 Kode 设为 kode/facade 后端容器并启用协程安全
final class Cache extends ServiceFacade
{
protected static function id(): string { return 'cache'; }
}
Cache::get('key'); // 经 Kode 容器解析,协程安全
use Kode\Http\Integration\QueueMiddleware;
use Kode\Http\Queue\Queue;
// bootstrap 中注入管理器(也可用 Queue::setManagerFromContainer($psr11))
Queue::setManager(\Kode\Queue\QueueManager::make([/* 连接配置 */]));
$app->pipe(QueueMiddleware::fromContainer(Kode::container()));
// 路由处理器内
Queue::push(SendMail::class, ['to' => $email]); // 仅收集,不阻塞响应
use Kode\Http\Integration\DistributedConfig;
use Kode\Http\Integration\ProcessWorkerMiddleware;
use Kode\Http\Integration\FiberCoroutineMiddleware;
use Kode\Http\Integration\ParallelMiddleware;
$config = new DistributedConfig('node-1');
$config->setEnabled(true);
$config->setNodes([
'node-1' => ['host' => '192.168.1.1', 'port' => 8080, 'weight' => 1],
'node-2' => ['host' => '192.168.1.2', 'port' => 8080, 'weight' => 1],
]);
$config->setLoadBalanceStrategy('round_robin');
$config->setCallTimeout(30.0);
$config->setMaxRetries(3);
$worker = new ProcessWorkerMiddleware(0, true, [
'pool_size' => 4,
'enable_stats' => true,
'distributed' => [
'enabled' => true,
'node_id' => 'worker-1',
'nodes' => [
'worker-1' => ['host' => '192.168.1.1', 'port' => 8080],
'worker-2' => ['host' => '192.168.1.2', 'port' => 8080],
],
],
]);
$app->use($worker);
$fiber = new FiberCoroutineMiddleware(10, 2048, [
'timeout' => 30,
'distributed' => [
'enabled' => true,
'node_id' => 'fiber-1',
'nodes' => [
'fiber-1' => ['host' => '192.168.1.1', 'port' => 8081],
'fiber-2' => ['host' => '192.168.1.2', 'port' => 8081],
],
],
]);
$app->use($fiber);
$parallel = new ParallelMiddleware(10, [
'distributed' => [
'enabled' => true,
'node_id' => 'parallel-1',
'nodes' => [
'parallel-1' => ['host' => '192.168.1.1', 'port' => 8082],
'parallel-2' => ['host' => '192.168.1.2', 'port' => 8082],
],
'load_balance_strategy' => 'least_load',
],
]);
$app->use($parallel);