woocommerce/.ai/skills/woocommerce-backend-dev/zh-cn/coding-conventions.md
2026-04-15 10:18:01 +08:00

150 lines
No EOL
3.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 常规编码规范
## 目录
- [代码清晰度和评论](#代码清晰度和评论)
- [WordPress 编码标准](#wordpress-编码标准)
- [空值合并运算符](#空值合并运算符)
- [三元运算符](#三元运算符)
- [call_user_func_array() 用法](#call_user_func_array-用法)
- [代码检查](#代码检查)
## 代码清晰性与注释
编写自解释的代码。谨慎使用注释——仅用于非显而易见的见解。
**良好 - 代码能自我解释:**
```php
if ( $order->is_draft() && $user->can_delete_drafts() ) {
$order->delete();
}
```
**避免 - 过度注释:**
```php
// 检查订单是否为草稿
if ( $order->is_draft() ) {
// 检查用户是否有权限
if ( $user->can_delete_drafts() ) {
// 删除订单
$order->delete();
}
}
```
**何时添加注释:**
- 不寻常的决定、变通方案或非显而易见的业务逻辑
- 性能考量
**何时不应添加注释:**
- 解释代码做什么(代码应该是自解释的)
- 重复陈述显而易见的内容
## WordPress 编码标准
关注 [WordPress 编码标准](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/)
- **Yoda 条件**`'true' === $value` 而非 `$value === 'true'`
- **间距**:运算符周围、括号内部使用空格
- **大括号**:左大括号在同一行,右大括号在新行
- **命名**:函数和变量使用 snake_case
## 空值合并运算符
使用 `??` 替代 `isset` 检查数组访问。
**推荐:**
```php
if ( 34 === ( $foo['bar'] ?? null ) ) {
// ...
}
$value = $options['setting'] ?? 'default';
```
**避免:**
```php
if ( isset( $foo['bar'] ) && 34 === $foo['bar'] ) {
// ...
}
if ( isset( $options['setting'] ) ) {
$value = $options['setting'];
} else {
$value = 'default';
}
```
## 三元运算符
对于简单的条件返回或赋值,优先使用三元运算符而非 if-else 语句,除非情况非常复杂。
**良好示例:**
```php
return $condition ? $true_value : $false_value;
$result = $is_enabled ? 'enabled' : 'disabled';
$price = $has_discount ? $product->get_sale_price() : $product->get_regular_price();
```
**应避免:**
```php
if ( $condition ) {
return $true_value;
}
return $false_value;
if ( $is_enabled ) {
$result = 'enabled';
} else {
$result = 'disabled';
}
```
**例外情况:** 当条件复杂或每个分支需要执行多条语句时,使用传统的 if-else 语句。
```php
// 当涉及复杂逻辑时,使用 if-else 是可以的
if ( $order->needs_shipping() && ! $order->has_valid_address() ) {
$this->logger->log( 'Invalid shipping address' );
$this->notify_customer( $order );
return false;
} else {
return true;
}
```
## call_user_func_array() 用法
在使用 `call_user_func_array()` 时,始终为参数参数使用**位置参数**(数字索引数组),而不是命名/关联数组。
该函数按顺序使用数组值并忽略关键字,因此命名关键字会产生误导。
**正确:**
```php
call_user_func_array( array( $obj, 'method' ), array( $code ) );
call_user_func_array( array( $obj, 'process' ), array( $id, $status, $data ) );
```
**错误:**
```php
call_user_func_array( array( $obj, 'method' ), array( 'country_code' => $code ) );
call_user_func_array( array( $obj, 'process' ), array( 'order_id' => $id, 'status' => $status ) );
```
## 代码检查
仅修复您当前分支中已添加或修改代码的检查错误。
除非特别要求,否则请勿修复无关代码中的检查错误。