本文目录导读:

针对 PHP 低代码连接器的需求,这里提供几种不同复杂度的实现方案,从轻量到标准化:
通用 API 连接器(最轻量)
适合快速对接 REST/SOAP API。
class GenericApiConnector {
private $baseUrl;
private $headers;
private $timeout;
public function __construct(string $baseUrl, array $headers = [], int $timeout = 30) {
$this->baseUrl = rtrim($baseUrl, '/');
$this->headers = $headers;
$this->timeout = $timeout;
}
// 通用请求方法
public function request(string $method, string $endpoint, array $data = []): array {
$url = $this->baseUrl . '/' . ltrim($endpoint, '/');
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => array_merge(
['Content-Type: application/json'],
$this->headers
)
]);
if (!empty($data) && in_array(strtoupper($method), ['POST', 'PUT', 'PATCH'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'status' => $httpCode,
'data' => json_decode($response, true) ?? $response
];
}
// 便捷方法
public function get(string $endpoint) { return $this->request('GET', $endpoint); }
public function post(string $endpoint, array $data) { return $this->request('POST', $endpoint, $data); }
public function put(string $endpoint, array $data) { return $this->request('PUT', $endpoint, $data); }
public function delete(string $endpoint) { return $this->request('DELETE', $endpoint); }
}
// 使用示例
$linker = new GenericApiConnector('https://api.example.com/v1', [
'Authorization: Bearer ' . $token
]);
$result = $linker->post('/orders', ['product_id' => 123, 'qty' => 2]);
数据库低代码连接器
适合快速构建 CRUD 操作,无需大量 SQL。
class DatabaseConnector {
private PDO $pdo;
private $table;
private $conditions = [];
public function __construct(PDO $pdo, string $table) {
$this->pdo = $pdo;
$this->table = $table;
}
// 链式查询构建
public function where(string $column, $value, string $operator = '='): self {
$this->conditions[] = "$column $operator :$column" . count($this->conditions);
return $this;
}
public function find(int $id): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
public function findAll(array $conditions = []): array {
$sql = "SELECT * FROM {$this->table}";
if (!empty($conditions)) {
$sql .= " WHERE " . implode(' AND ', array_map(function($col, $val) {
return "$col = :$col";
}, array_keys($conditions), $conditions));
}
$stmt = $this->pdo->prepare($sql);
$stmt->execute($conditions);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function create(array $data): int {
$columns = implode(', ', array_keys($data));
$placeholders = ':' . implode(', :', array_keys($data));
$sql = "INSERT INTO {$this->table} ($columns) VALUES ($placeholders)";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
return (int)$this->pdo->lastInsertId();
}
public function update(int $id, array $data): bool {
$set = implode(', ', array_map(fn($col) => "$col = :$col", array_keys($data)));
$data['id'] = $id;
$sql = "UPDATE {$this->table} SET $set WHERE id = :id";
return $this->pdo->prepare($sql)->execute($data);
}
public function delete(int $id): bool {
$sql = "DELETE FROM {$this->table} WHERE id = :id";
return $this->pdo->prepare($sql)->execute(['id' => $id]);
}
}
// 使用示例
$connector = new DatabaseConnector($pdo, 'users');
$user = $connector->find(1);
$newId = $connector->create(['name' => 'John', 'email' => 'john@example.com']);
可配置的规则引擎连接器
适合根据配置动态执行不同逻辑。
class RuleBasedConnector {
private array $rules;
private $data;
public function __construct(array $rules) {
$this->rules = $rules;
}
public function setData(array $data): self {
$this->data = $data;
return $this;
}
public function execute(): array {
$results = [];
foreach ($this->rules as $ruleName => $config) {
if (!$this->evaluateCondition($config['when'] ?? [])) {
continue;
}
$results[$ruleName] = $this->performAction(
$config['action'] ?? 'return',
$config['params'] ?? []
);
}
return $results;
}
private function evaluateCondition(array $condition): bool {
if (empty($condition)) return true;
$field = $condition['field'] ?? null;
$operator = $condition['operator'] ?? '=';
$value = $condition['value'] ?? null;
if (!isset($this->data[$field])) return false;
$actual = $this->data[$field];
switch ($operator) {
case '>': return $actual > $value;
case '<': return $actual < $value;
case '=': return $actual == $value;
case '!=': return $actual != $value;
case 'in': return in_array($actual, (array)$value);
case 'contains': return str_contains($actual, $value);
default: return false;
}
}
private function performAction(string $action, array $params) {
switch ($action) {
case 'return':
return $params;
case 'divide':
return $this->data[$params['dividend']] / $this->data[$params['divisor']];
case 'concat':
return implode($params['separator'] ?? '',
array_map(fn($field) => $this->data[$field], $params['fields'])
);
case 'calculate':
return eval("return " . $this->replaceVariables($params['formula']) . ";");
default:
throw new \RuntimeException("Unknown action: $action");
}
}
private function replaceVariables(string $formula): string {
return preg_replace_callback('/\{(\w+)\}/', function($matches) {
return $this->data[$matches[1]] ?? 0;
}, $formula);
}
}
// 使用示例
$connector = new RuleBasedConnector([
'discount' => [
'when' => ['field' => 'total', 'operator' => '>', 'value' => 100],
'action' => 'calculate',
'params' => ['formula' => '(total - 10) * 0.9']
],
'message' => [
'when' => ['field' => 'username', 'operator' => 'contains', 'value' => 'admin'],
'action' => 'concat',
'params' => ['fields' => ['prefix', 'username'], 'separator' => ' ']
]
]);
$result = $connector->setData([
'total' => 200,
'username' => 'admin_user',
'prefix' => 'Welcome'
])->execute();
标准化连接器(类规范化)
interface ConnectorInterface {
public function connect(): void;
public function execute(array $operation, array $params = []): mixed;
public function disconnect(): void;
}
abstract class AbstractConnector implements ConnectorInterface {
protected $connection;
protected $config;
public function __construct(array $config) {
$this->config = $config;
}
public function __destruct() {
$this->disconnect();
}
protected function validateConfig(array $requiredKeys): void {
foreach ($requiredKeys as $key) {
if (!isset($this->config[$key])) {
throw new \InvalidArgumentException("Missing config: $key");
}
}
}
}
class MySQLConnector extends AbstractConnector {
public function connect(): void {
$this->validateConfig(['host', 'database', 'username', 'password']);
$dsn = "mysql:host={$this->config['host']};dbname={$this->config['database']};charset=utf8mb4";
$this->connection = new PDO($dsn, $this->config['username'], $this->config['password']);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function execute(array $operation, array $params = []): mixed {
$method = $operation['method'] ?? 'query';
$sql = $operation['sql'];
try {
$stmt = $this->connection->prepare($sql);
$stmt->execute($params);
switch ($method) {
case 'fetchAll': return $stmt->fetchAll(PDO::FETCH_ASSOC);
case 'fetch': return $stmt->fetch(PDO::FETCH_ASSOC);
case 'count': return $stmt->rowCount();
default: return $stmt->execute();
}
} catch (PDOException $e) {
throw new RuntimeException("Query failed: {$e->getMessage()}");
}
}
public function disconnect(): void {
$this->connection = null;
}
}
推荐库/框架
| 库/框架 | 特点 | 适合场景 |
|---|---|---|
| slim/psr7 | 轻量、中间件支持 | 构建简单 REST API |
| guzzlehttp/guzzle | 功能全面的 HTTP 客户端 | 需要高级请求处理 |
| doctrine/dbal | 数据库抽象层 | 复杂数据库操作 |
| symfony/process | 进程管理 | 需要调用外部命令 |
| phpunit/php-codecoverage | 代码覆盖率 | 调试连接器 |
调试建议
// 开启调试模式
class DebuggableApiConnector extends GenericApiConnector {
private $dbug = false;
public function enableDebug(): self {
$this->dbug = true;
return $this;
}
protected function log(string $message, array $context = []): void {
if ($this->dbug) {
error_log(sprintf(
'[%s] %s %s',
date('Y-m-d H:i:s'),
$message,
json_encode($context)
));
}
}
public function request(string $method, string $endpoint, array $data = []): array {
$this->log('Before request', compact('method', 'endpoint', 'data'));
$result = parent::request($method, $endpoint, $data);
$this->log('After request', $result);
return $result;
}
}
最佳实践建议
- 遵循 PSR 标准:PSR-4 自动加载、PSR-7 HTTP 消息、PSR-12 代码风格
- 使用依赖注入容器:如 PHP-DI 或 Symfony DI
- 配置与代码分离:使用 YAML/JSON 配置文件定义连接器参数
- 加入缓存层:对高频请求使用 Redis/Memcached
- 统一错误处理:自定义异常类和错误码
- 单元测试:为每个连接器编写测试用例
- 日志记录:记录每次调用的完整请求/响应详情
这些方案覆盖了从几分钟到几小时开发时间的各类场景,可以根据具体项目需求选择合适的实现。