news 2026/7/17 11:27:50

PHP 15 个高效开发的小技巧

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PHP 15 个高效开发的小技巧

让类型系统为你保驾护航

declare(strict_types=1);

function calculatePriceWithTax(float $price, float $taxRate): float {

return $price * (1 + $taxRate);

}

优势:类型错误会立即显现,而不是在后期才出现并难以追踪。

使用空值合并和空安全操作符

简化空值检查:

// 空值合并

$username = $_GET['user'] ?? 'guest';

// 空安全操作符

$street = $order?->customer?->address?->street;

// 空值合并赋值

$config['timeout'] ??= 30;

使用 match 替代 switch

更简洁的条件分支:

$statusText = match ($statusCode) {

200, 201 => '成功',

400 => '错误请求',

404 => '未找到',

500 => '服务器错误',

default => '未知状态',

};

使用箭头函数简化回调

$prices = [12.5, 10.0, 3.5];

$pricesWithTax = array_map(fn($price) => round($price * 1.11, 2), $prices);

数组辅助函数

// 从用户数组中提取邮箱

$emails = array_column($users, 'email');

// 按ID索引

$indexedById = array_column($users, null, 'id');

// 计算购物车总价

$total = array_reduce($cart,

fn($sum, $item) => $sum + $item['quantity'] * $item['price'],

0.0

);

使用 filter_var 验证输入

$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);

$ip = filter_var($_SERVER['REMOTE_ADDR'] ?? '', FILTER_VALIDATE_IP);

if (!$email) { /* 处理邮箱格式错误 */ }

安全的字符串处理

// 去除空白字符

$name = trim((string)($_POST['name'] ?? ''));

// 安全比较(防止时序攻击)

if (hash_equals($knownToken, $providedToken)) {

// 验证通过,继续执行

}

使用 DateTimeImmutable 处理日期

$timezone = new DateTimeZone('Asia/Shanghai');

$now = new DateTimeImmutable('now', $timezone);

// 计算两天后的上午9点

$deliveryTime = $now->modify('+2 days')->setTime(9, 0);

使用生成器处理大文件

/**

* 读取CSV文件生成器

* @param string $filePath CSV文件路径

* @return Generator 返回生成器,每次yield一行数据

* @throws RuntimeException 当文件无法打开时抛出异常

*/

function readCsvFile(string $filePath): Generator {

$handle = fopen($filePath, 'r');

if (!$handle) {

throw new RuntimeException("无法打开文件: $filePath");

}

try {

while (($row = fgetcsv($handle)) !== false) {

yield $row;

}

} finally {

fclose($handle);

}

}

// 使用示例

foreach (readCsvFile('/path/to/orders.csv') as [$id, $email, $amount]) {

// 处理每一行数据

}

使用 PDO 预处理语句和事务

// 数据库连接配置

$dbConfig = [

'host' => 'localhost',

'dbname' => 'shop',

'charset' => 'utf8mb4',

'username' => 'username',

'password' => 'password'

];

// 创建PDO实例

$dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";

$pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password'], [

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // 设置错误模式为异常

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 设置默认获取模式为关联数组

PDO::ATTR_EMULATE_PREPARES => false, // 禁用预处理语句的模拟

]);

$pdo->beginTransaction();

try {

$stmt = $pdo->prepare('INSERT INTO orders (email, amount) VALUES (:email, :amount)');

foreach ($orders as $order) {

$stmt->execute([

':email' => $order['email'],

':amount' => $order['amount']

]);

}

$pdo->commit();

} catch (Throwable $e) {

$pdo->rollBack();

throw $e;

}

使用 Composer 自动加载

在 composer.json 中配置:

{

"autoload": {

"psr-4": {

"App\\": "src/"

}

}

}

运行 composer dump-autoload 使配置生效。

使用属性(PHP 8+)

#[

Attribute

]

class Route {

public function __construct(

public string $method,

public string $path

) {}

}

#[Route('GET', '/health-check')]

function healthCheck(): array {

return ['status' => '成功'];

}

使用 SPL 迭代器

$dir = new RecursiveDirectoryIterator(__DIR__ . '/logs');

$iterator = new RecursiveIteratorIterator($dir);

foreach ($iterator as $path => $fileInfo) {

if ($fileInfo->isFile() && str_ends_with($path, '.log')) {

// 处理日志文件内容

}

}

使用特定的异常类型

/**

* 订单未找到异常

*/

class OrderNotFoundException extends RuntimeException {}

function getOrder(PDO $db, int $orderId): array {

$stmt = $db->prepare('SELECT * FROM orders WHERE id = :id');

$stmt->execute([':id' => $orderId]);

$row = $stmt->fetch();

if (!$row) {

throw new OrderNotFoundException("Order with ID $orderId not found");

}

return $row;

}

创建命令行脚本

#!/usr/bin/env php

<?php

declare(strict_types=1);

$options = getopt('', ['path:']);

$filePath = $options['path'] ?? 'input.csv';

foreach (readCsvFile($filePath) as $row) {

// 处理每一行

}

实战示例:CSV 导入数据库

$db->beginTransaction();

$stmt = $db->prepare('INSERT INTO orders (id, email, amount, created_at) VALUES (:id, :email, :amount, :created_at)');

$batch = 0;

foreach (readCsvFile('orders.csv') as $lineNumber => $row) {

if ($lineNumber === 0) continue; // 跳过CSV文件的标题行

[$id, $email, $amount, $createdAt] = $row;

// 数据验证

$email = filter_var($email, FILTER_VALIDATE_EMAIL);

$amount = is_numeric($amount) ? (float)$amount : null;

if (!$email || $amount === null) {

// 记录无效数据行

error_log("第 {$lineNumber} 行数据无效: " . json_encode($row));

continue;

}

// 日期时间格式化

$timezone = new DateTimeZone('Asia/Shanghai');

$createdAt = (new DateTimeImmutable($createdAt, $timezone))->format('Y-m-d H:i:s');

// 执行数据库插入

$stmt->execute([

':id' => (int)$id,

':email' => $email,

':amount' => $amount,

':created_at' => $createdAt,

]);

// 每处理1000条记录提交一次事务

if ((++$batch % 1000) === 0) {

$db->commit();

$db->beginTransaction();

}

}

$db->commit();

总结

这些技巧可以帮助你:

编写更健壮的代码

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

电视盒子刷机终极方案:高安版设备完整避坑指南

你猜我发现了什么&#xff1f;一台被认为"无法刷机"的高安版电视盒子&#xff0c;现在居然完美运行着Armbian系统&#xff01;&#x1f680; 经过72小时的持续探索&#xff0c;我终于找到了解决高安设备限制的完整方案。 【免费下载链接】amlogic-s9xxx-armbian amlo…

作者头像 李华
网站建设 2026/7/16 19:17:32

ssm 框架的校园二手交易市场系统

项目概述校园二手商品市场系统基于SSM框架&#xff08;SpringSpringMVCMyBatis&#xff09;开发&#xff0c;旨在为在校学生提供二手商品交易平台。系统包含用户管理、商品发布、交易撮合、消息通知等核心功能模块。技术栈后端框架&#xff1a;Spring 5.x SpringMVC MyBatis …

作者头像 李华
网站建设 2026/7/17 6:57:59

Tabula终极指南:5步快速从PDF提取表格数据的完整教程

Tabula终极指南&#xff1a;5步快速从PDF提取表格数据的完整教程 【免费下载链接】tabula Tabula is a tool for liberating data tables trapped inside PDF files 项目地址: https://gitcode.com/gh_mirrors/ta/tabula Tabula是一款革命性的开源工具&#xff0c;专门用…

作者头像 李华
网站建设 2026/7/17 10:08:30

维修钛蝶阀需要用到哪些工具?

维修钛蝶阀时&#xff0c;需根据拆卸、安装、检测、密封处理等核心环节&#xff0c;准备以下专业工具及辅助设备&#xff0c;以确保操作安全与维修质量&#xff1a; 今天&#xff0c;就来详细探讨一下&#xff0c;在维修捷斯特钛蝶阀时&#xff0c;需要准备哪些工具和设备。一、…

作者头像 李华
网站建设 2026/7/18 3:12:01

5大裂缝数据集全集:计算机视觉研究的终极资源库

5大裂缝数据集全集&#xff1a;计算机视觉研究的终极资源库 【免费下载链接】裂缝开源数据集下载仓库 - **CRACK50**: 包含50张裂缝图像的数据集。- **GAPs384**: 包含384张裂缝图像的数据集。- **CFD**: 裂缝检测数据集。- **AEL**: 裂缝分析数据集。- **cracktree200**: 包含…

作者头像 李华
网站建设 2026/7/17 4:57:52

【光照】Unity[PBR]环境光中的[镜面IBL]

核心原理镜面IBL&#xff08;Image-Based Lighting - Specular&#xff09;是基于图像光照技术中的镜面反射部分&#xff0c;其核心技术是分裂求和近似法&#xff08;Split Sum Approximation&#xff09;。该方法将复杂的实时镜面积分拆分为预滤波环境贴图和BRDF积分两部分&am…

作者头像 李华