PHP微服务架构与RESTful设计
微服务架构将应用拆分成多个独立服务。PHP在微服务中可以作为服务提供者。今天说说PHP微服务和RESTful API的设计。
微服务间通信用HTTP或RPC。
```php
class ServiceClient
{
private array $services = [];
public function registerService(string $name, string $host, int $port): void
{
$this->services[$name] = compact('host', 'port');
}
public function call(string $service, string $method, string $path, array $data = []): array
{
$config = $this->services[$service] ?? null;
if ($config === null) throw new RuntimeException("服务不可达: $service");
$url = "http://{$config['host']}:{$config['port']}{$path}";
$ch = curl_init($url);
$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5];
if ($method === 'POST') {
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = json_encode($data);
$options[CURLOPT_HTTPHEADER] = ['Content-Type: application/json'];
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ['status' => $httpCode, 'body' => json_decode($response, true) ?? []];
}
}
$client = new ServiceClient();
$client->registerService('user-service', '192.168.1.10', 9001);
$result = $client->call('user-service', 'GET', '/api/users/1');
echo "状态: {$result['status']}\n";
?>
RESTful路由设计。
```php
class RestRouter
{
private array $routes = [];
public function resource(string $base, string $controller): void
{
$this->get($base, [$controller, 'index']);
$this->post($base, [$controller, 'store']);
$this->get("$base/{id}", [$controller, 'show']);
$this->put("$base/{id}", [$controller, 'update']);
$this->delete("$base/{id}", [$controller, 'destroy']);
}
public function get(string $path, callable $handler): void
{
$this->routes['GET'][] = compact('path', 'handler');
}
public function post(string $path, callable $handler): void
{
$this->routes['POST'][] = compact('path', 'handler');
}
public function put(string $path, callable $handler): void
{
$this->routes['PUT'][] = compact('path', 'handler');
}
public function delete(string $path, callable $handler): void
{
$this->routes['DELETE'][] = compact('path', 'handler');
}
public function dispatch(string $method, string $uri): void
{
$uri = parse_url($uri, PHP_URL_PATH);
foreach ($this->routes[$method] ?? [] as $route) {
$pattern = preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $route['path']);
$pattern = '#^' . $pattern . '$#';
if (preg_match($pattern, $uri, $matches)) {
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
header('Content-Type: application/json');
echo json_encode(($route['handler'])($params), JSON_UNESCAPED_UNICODE);
return;
}
}
http_response_code(404);
echo json_encode(['error' => 'Not Found']);
}
}
class UserController
{
public static function index(): array
{
return ['users' => [['id' => 1, 'name' => '张三']]];
}
public static function show(array $params): array
{
return ['user' => ['id' => (int)$params['id'], 'name' => '用户']];
}
public static function store(): array
{
$input = json_decode(file_get_contents('php://input'), true);
return ['message' => '创建成功', 'data' => $input];
}
}
?>
微服务API的统一响应格式。
```php
class ApiResponse
{
public static function success(mixed $data = null, string $message = 'success'): string
{
return json_encode(['code' => 0, 'message' => $message, 'data' => $data], JSON_UNESCAPED_UNICODE);
}
public static function error(string $message, int $code = -1): string
{
return json_encode(['code' => $code, 'message' => $message], JSON_UNESCAPED_UNICODE);
}
public static function paginate(array $items, int $total, int $page, int $perPage): string
{
return json_encode([
'code' => 0,
'message' => 'success',
'data' => [
'items' => $items,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_pages' => ceil($total / $perPage),
],
], JSON_UNESCAPED_UNICODE);
}
}
?>
微服务架构带来了灵活性,也增加了复杂性。服务发现、负载均衡、分布式追踪等问题需要解决。对于大多数团队来说,从单体开始,在确实需要的时候才拆分微服务,是比较务实的方式。
PHP微服务架构与RESTful设计
张小明
前端开发工程师
新格伦爆炸冲击波:AST的危机与卫星直连未来
2026 年 5 月 28 日,佛罗里达州卡纳维拉尔角的夜空被一道刺眼的火球瞬间照亮。蓝色起源的新格伦火箭在静态点火测试中突发剧烈爆炸,98 米高的箭体在数秒内化为碎片,专用发射台也被爆炸冲击波严重损毁。这场事故不仅让贝索斯筹备多年的重型火箭…
主流的工业3D相机及其区别
机器视觉中,3D相机则通过获取三维点云数据,让机器真正“看懂”了世界。目前市场上主流的工业3D相机有结构光、ToF、双目视觉、激光三角测量等,它们之间到底有什么区别?今天我们就来一探究竟。01 结构光:主动编码 三角…
别再只会用dd了!手把手教你用FIO在CentOS 7上精准测试磁盘性能(附iostat监控)
告别dd时代:FIO在CentOS 7下的专业磁盘性能评测实战当我们需要评估一块新硬盘的实际性能,或者排查数据库的I/O瓶颈时,很多人第一反应就是打开终端输入dd if/dev/zero oftestfile bs1G count1。这种简单粗暴的方法虽然能快速得到一个数字&…
全球氮化硼粉市场深度研究报告
氮化硼粉末是一种具有六方层状或立方超硬结构的先进陶瓷粉体材料。它以极高的热导率、卓越的电绝缘性、出色的高温稳定性(2800C)及化学惰性为核心优势,兼具低摩擦系数与中子吸收功能。这种“白色石墨烯”可定制为片状、球形、多孔等形态&…
3分钟掌握Python通达信数据接口:mootdx完整使用指南
3分钟掌握Python通达信数据接口:mootdx完整使用指南 【免费下载链接】mootdx 通达信数据读取的一个简便使用封装 项目地址: https://gitcode.com/GitHub_Trending/mo/mootdx 还在为金融数据分析的数据源发愁吗?商业API价格昂贵,网络爬…
Mythos如何实现AI安全能力的断层式跃迁
1. 这不是一次普通模型发布:它是一道分水岭式的安全能力跃迁你可能已经刷到过“Anthropic发布Claude Mythos”这条新闻,但如果你只把它当成又一个“更强的Claude”,那你就错过了过去五年AI安全领域最值得细读的一份技术白皮书。这不是参数堆叠…