news 2026/6/9 11:44:02

PHP微服务架构与RESTful设计

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PHP微服务架构与RESTful设计

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);
}
}
?>

微服务架构带来了灵活性,也增加了复杂性。服务发现、负载均衡、分布式追踪等问题需要解决。对于大多数团队来说,从单体开始,在确实需要的时候才拆分微服务,是比较务实的方式。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/9 11:43:52

新格伦爆炸冲击波:AST的危机与卫星直连未来

2026 年 5 月 28 日&#xff0c;佛罗里达州卡纳维拉尔角的夜空被一道刺眼的火球瞬间照亮。蓝色起源的新格伦火箭在静态点火测试中突发剧烈爆炸&#xff0c;98 米高的箭体在数秒内化为碎片&#xff0c;专用发射台也被爆炸冲击波严重损毁。这场事故不仅让贝索斯筹备多年的重型火箭…

作者头像 李华
网站建设 2026/6/9 11:42:44

主流的工业3D相机及其区别

机器视觉中&#xff0c;3D相机则通过获取三维点云数据&#xff0c;让机器真正“看懂”了世界。目前市场上主流的工业3D相机有结构光、ToF、双目视觉、激光三角测量等&#xff0c;它们之间到底有什么区别&#xff1f;今天我们就来一探究竟。01 结构光&#xff1a;主动编码 三角…

作者头像 李华
网站建设 2026/6/9 11:41:25

全球氮化硼粉市场深度研究报告

氮化硼粉末是一种具有六方层状或立方超硬结构的先进陶瓷粉体材料。它以极高的热导率、卓越的电绝缘性、出色的高温稳定性&#xff08;2800C&#xff09;及化学惰性为核心优势&#xff0c;兼具低摩擦系数与中子吸收功能。这种“白色石墨烯”可定制为片状、球形、多孔等形态&…

作者头像 李华
网站建设 2026/6/9 11:41:22

3分钟掌握Python通达信数据接口:mootdx完整使用指南

3分钟掌握Python通达信数据接口&#xff1a;mootdx完整使用指南 【免费下载链接】mootdx 通达信数据读取的一个简便使用封装 项目地址: https://gitcode.com/GitHub_Trending/mo/mootdx 还在为金融数据分析的数据源发愁吗&#xff1f;商业API价格昂贵&#xff0c;网络爬…

作者头像 李华
网站建设 2026/6/9 11:39:43

Mythos如何实现AI安全能力的断层式跃迁

1. 这不是一次普通模型发布&#xff1a;它是一道分水岭式的安全能力跃迁你可能已经刷到过“Anthropic发布Claude Mythos”这条新闻&#xff0c;但如果你只把它当成又一个“更强的Claude”&#xff0c;那你就错过了过去五年AI安全领域最值得细读的一份技术白皮书。这不是参数堆叠…

作者头像 李华