name: php description: 使用生成器、SPL和PHP 8+特性编写现代PHP。用于PHP开发或优化。
PHP开发
编写现代、高性能的PHP代码。
何时使用
- 编写PHP代码
- PHP 8+特性
- 性能优化
- Laravel/Symfony开发
现代PHP模式
类型系统(PHP 8+)
// 联合类型
function process(int|string $id): array|false {
// ...
}
// 构造函数属性提升
class User {
public function __construct(
public readonly string $name,
public readonly string $email,
private ?int $age = null,
) {}
}
// 枚举
enum Status: string {
case Pending = 'pending';
case Active = 'active';
case Completed = 'completed';
}
// 匹配表达式
$result = match($status) {
Status::Pending => '等待',
Status::Active => '进行中',
Status::Completed => '完成',
};
生成器
// 内存高效迭代
function readLargeFile(string $path): Generator {
$handle = fopen($path, 'r');
while (($line = fgets($handle)) !== false) {
yield trim($line);
}
fclose($handle);
}
// 使用
foreach (readLargeFile('huge.csv') as $line) {
processLine($line);
}
// 带键的生成器
function parseCSV(string $path): Generator {
$handle = fopen($path, 'r');
$headers = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
yield array_combine($headers, $row);
}
fclose($handle);
}
SPL数据结构
// 优先队列
$queue = new SplPriorityQueue();
$queue->insert('low', 1);
$queue->insert('high', 10);
$queue->insert('medium', 5);
while (!$queue->isEmpty()) {
echo $queue->extract(); // high, medium, low
}
// 固定数组(内存高效)
$arr = new SplFixedArray(1000);
$arr[0] = 'value';
错误处理
// 自定义异常
class ValidationException extends Exception {
public function __construct(
public readonly string $field,
string $message,
) {
parent::__construct($message);
}
}
// 多种类型的try-catch
try {
process($data);
} catch (ValidationException $e) {
log("验证失败: {$e->field}");
} catch (RuntimeException $e) {
log("运行时错误: {$e->getMessage()}");
} finally {
cleanup();
}
属性(PHP 8)
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public string $path,
public string $method = 'GET',
) {}
}
class Controller {
#[Route('/users', 'GET')]
public function listUsers(): array {
// ...
}
}
最佳实践
- 使用严格类型:
declare(strict_types=1); - 遵循PSR-12编码标准
- 使用Composer进行自动加载
- 优先使用内置函数而非自定义函数
- 对大型数据集使用生成器
示例
输入: “优化此PHP代码” 操作: 使用Xdebug进行分析,使用生成器,利用SPL结构
输入: “现代化到PHP 8” 操作: 添加类型提示,使用匹配/枚举,构造函数提升