翻译文档

This commit is contained in:
yinjianm
2026-02-22 04:13:42 +08:00
parent 267aeec5ba
commit 2d14e22322
13 changed files with 683 additions and 687 deletions
+151 -155
View File
@@ -1,26 +1,26 @@
# XBoard Plugin Development Guide
# XBoard 插件开发指南
## 📦 Plugin Structure
## 插件结构
Each plugin is an independent directory with the following structure:
每个插件都是一个独立目录,推荐结构如下:
```
plugins/
└── YourPlugin/ # Plugin directory (PascalCase naming)
├── Plugin.php # Main plugin class (required)
├── config.json # Plugin configuration (required)
└── YourPlugin/ # 插件目录(PascalCase 命名)
├── Plugin.php # 插件主类(必需)
├── config.json # 插件配置(必需)
├── routes/
│ └── api.php # API routes
├── Controllers/ # Controllers directory
│ └── api.php # API 路由
├── Controllers/ # 控制器目录
│ └── YourController.php
├── Commands/ # Artisan commands directory
├── Commands/ # Artisan 命令目录
│ └── YourCommand.php
└── README.md # Documentation
└── README.md # 文档说明
```
## 🚀 Quick Start
## 快速开始
### 1. Create Configuration File `config.json`
### 1. 创建配置文件 `config.json`
```json
{
@@ -49,7 +49,7 @@ plugins/
}
```
### 2. Create Main Plugin Class `Plugin.php`
### 2. 创建插件主类 `Plugin.php`
```php
<?php
@@ -75,9 +75,9 @@ class Plugin extends AbstractPlugin
}
```
### 3. Create Controller
### 3. 创建控制器
**Recommended approach: Extend PluginController**
推荐做法:继承 `PluginController`
```php
<?php
@@ -102,7 +102,7 @@ class YourController extends PluginController
}
```
### 4. Create Routes `routes/api.php`
### 4. 创建路由 `routes/api.php`
```php
<?php
@@ -117,9 +117,9 @@ Route::group([
});
```
## 🔧 Configuration Access
## 配置访问
In controllers, you can easily access plugin configuration:
在控制器中可直接访问插件配置:
```php
// Get single configuration
@@ -132,33 +132,33 @@ $allConfig = $this->getConfig();
$enabled = $this->isPluginEnabled();
```
## 🎣 Hook System
## Hook 系统
### Popular Hooks (Recommended to follow)
### 常用 Hook(建议优先关注)
XBoard has built-in hooks for many business-critical nodes. Plugin developers can flexibly extend through `filter` or `listen` methods. Here are the most commonly used and valuable hooks:
XBoard 在多个关键业务节点提供了内置 hook。插件可通过 `filter` `listen` 扩展行为。
| Hook Name | Type | Typical Parameters | Description |
| ------------------------- | ------ | ----------------------- | ---------------- |
| user.register.before | action | Request | Before user registration |
| user.register.after | action | User | After user registration |
| user.login.after | action | User | After user login |
| user.password.reset.after | action | User | After password reset |
| order.cancel.before | action | Order | Before order cancellation |
| order.cancel.after | action | Order | After order cancellation |
| payment.notify.before | action | method, uuid, request | Before payment callback |
| payment.notify.verified | action | array | Payment callback verification successful |
| payment.notify.failed | action | method, uuid, request | Payment callback verification failed |
| traffic.reset.after | action | User | After traffic reset |
| ticket.create.after | action | Ticket | After ticket creation |
| ticket.reply.user.after | action | Ticket | After user replies to ticket |
| ticket.close.after | action | Ticket | After ticket closure |
| Hook 名称 | 类型 | 常见参数 | 说明 |
| ------------------------- | ------ | ----------------------- | ---- |
| user.register.before | action | Request | 用户注册前 |
| user.register.after | action | User | 用户注册后 |
| user.login.after | action | User | 用户登录后 |
| user.password.reset.after | action | User | 密码重置后 |
| order.cancel.before | action | Order | 订单取消前 |
| order.cancel.after | action | Order | 订单取消后 |
| payment.notify.before | action | method, uuid, request | 支付回调校验前 |
| payment.notify.verified | action | array | 支付回调校验成功 |
| payment.notify.failed | action | method, uuid, request | 支付回调校验失败 |
| traffic.reset.after | action | User | 流量重置后 |
| ticket.create.after | action | Ticket | 工单创建后 |
| ticket.reply.user.after | action | Ticket | 用户回复工单后 |
| ticket.close.after | action | Ticket | 工单关闭后 |
> ⚡️ The hook system will continue to expand. Developers can always follow this documentation and the `php artisan hook:list` command to get the latest supported hooks.
> hook 能力会持续扩展。可结合本文与 `php artisan hook:list` 获取最新支持列表。
### Filter Hooks
### Filter Hook
Used to modify data:
用于修改数据:
```php
// In Plugin.php boot() method
@@ -169,9 +169,9 @@ $this->filter('guest_comm_config', function ($config) {
});
```
### Action Hooks
### Action Hook
Used to execute operations:
用于执行动作:
```php
$this->listen('user.created', function ($user) {
@@ -180,11 +180,11 @@ $this->listen('user.created', function ($user) {
});
```
## 📝 Real Example: Telegram Login Plugin
## 实战示例:Telegram 登录插件
Using TelegramLogin plugin as an example to demonstrate complete implementation:
下面使用 TelegramLogin 插件展示完整实现思路。
**Main Plugin Class** (23 lines):
### 插件主类
```php
<?php
@@ -207,7 +207,7 @@ class Plugin extends AbstractPlugin
}
```
**Controller** (extends PluginController):
### 控制器(继承 `PluginController`
```php
class TelegramLoginController extends PluginController
@@ -230,11 +230,9 @@ class TelegramLoginController extends PluginController
}
```
## ⏰ Plugin Scheduled Tasks (Scheduler)
## 插件定时任务(Scheduler
Plugins can register their own scheduled tasks by implementing the `schedule(Schedule $schedule)` method in the main class.
**Example:**
插件可在主类中实现 `schedule(Schedule $schedule)` 方法来注册定时任务。
```php
use Illuminate\Console\Scheduling\Schedule;
@@ -252,27 +250,27 @@ class Plugin extends AbstractPlugin
}
```
- Just implement the `schedule()` method in Plugin.php.
- All plugin scheduled tasks will be automatically scheduled by the main program.
- Supports all Laravel scheduler usage.
- 只需在 `Plugin.php` 中实现 `schedule()`
- 主程序会自动调度所有插件任务。
- 支持 Laravel Scheduler 的全部能力。
## 🖥️ Plugin Artisan Commands
## 插件 Artisan 命令
Plugins can automatically register Artisan commands by creating command classes in the `Commands/` directory.
插件启用后,会自动加载 `Commands/` 目录中的命令类。
### Command Directory Structure
### 命令目录结构
```
plugins/YourPlugin/
├── Commands/
│ ├── TestCommand.php # Test command
│ ├── BackupCommand.php # Backup command
│ └── CleanupCommand.php # Cleanup command
│ ├── TestCommand.php # 测试命令
│ ├── BackupCommand.php # 备份命令
│ └── CleanupCommand.php # 清理命令
```
### Create Command Class
### 创建命令类
**Example: TestCommand.php**
示例:`TestCommand.php`
```php
<?php
@@ -333,13 +331,13 @@ class TestCommand extends Command
}
```
### Automatic Command Registration
### 自动注册规则
- ✅ Automatically register all commands in `Commands/` directory when plugin is enabled
- ✅ Command namespace automatically set to `Plugin\YourPlugin\Commands`
- ✅ Supports all Laravel command features (arguments, options, interaction, etc.)
- 插件启用时,自动注册 `Commands/` 目录下全部命令类。
- 命令命名空间自动按 `Plugin\YourPlugin\Commands` 解析。
- 支持 Laravel 命令全部能力(参数、选项、交互等)。
### Usage Examples
### 使用示例
```bash
# Test command
@@ -352,25 +350,25 @@ php artisan your-plugin:test info
php artisan your-plugin:test --help
```
### Best Practices
### 命令开发建议
1. **Command Naming**: Use `plugin-name:action` format, e.g., `telegram:test`
2. **Error Handling**: Wrap main logic with try-catch
3. **Return Values**: Return 0 for success, 1 for failure
4. **User Friendly**: Provide clear help information and error messages
5. **Type Declarations**: Use PHP 8.2 type declarations
1. **命令命名**:使用 `plugin-name:action`,例如 `telegram:test`
2. **异常处理**:主流程建议统一 `try-catch`
3. **返回码规范**:成功返回 `0`,失败返回 `1`
4. **可用性**:提供清晰的帮助信息和错误提示。
5. **类型声明**:建议使用 PHP 8.2 类型声明。
## 🛠️ Development Tools
## 开发工具与基础能力
### Controller Base Class Selection
### 控制器基类选择
**Method 1: Extend PluginController (Recommended)**
#### 方案一:继承 `PluginController`(推荐)
- Automatic configuration access: `$this->getConfig()`
- Automatic status checking: `$this->beforePluginAction()`
- Unified error handling
- 自动配置读取:`$this->getConfig()`
- 自动状态检查:`$this->beforePluginAction()`
- 统一返回与错误处理
**Method 2: Use HasPluginConfig Trait**
#### 方案二:使用 `HasPluginConfig` Trait
```php
use App\Http\Controllers\Controller;
@@ -388,37 +386,37 @@ class YourController extends Controller
}
```
### Configuration Types
### 配置类型
Supported configuration types:
支持以下配置类型:
- `string` - String
- `number` - Number
- `boolean` - Boolean
- `json` - Array
- `string`:字符串
- `number`:数字
- `boolean`:布尔值
- `json`:数组
- `yaml`
## 🎯 Best Practices
## 通用最佳实践
### 1. Concise Main Class
### 1. 保持主类简洁
- Plugin main class should be as concise as possible
- Mainly used for registering hooks and routes
- Complex logic should be placed in controllers or services
- `Plugin.php` 只保留启动相关逻辑。
- 主要负责注册 hooks、路由、调度等入口。
- 复杂业务放到 Controller 或 Service
### 2. Configuration Management
### 2. 统一配置管理
- Define all configuration items in `config.json`
- Use `$this->getConfig()` to access configuration
- Provide default values for all configurations
- 所有配置都在 `config.json` 明确定义。
- 通过 `$this->getConfig()` 读取。
- 所有项建议提供默认值。
### 3. Route Design
### 3. 路由设计清晰
- Use semantic route prefixes
- Place API routes in `routes/api.php`
- Place Web routes in `routes/web.php`
- 使用语义化前缀。
- API 路由放在 `routes/api.php`
- Web 路由放在 `routes/web.php`
### 4. Error Handling
### 4. 完善错误处理
```php
public function handle(Request $request)
@@ -437,16 +435,16 @@ public function handle(Request $request)
}
```
## 🔍 Debugging Tips
## 调试技巧
### 1. Logging
### 1. 日志记录
```php
\Log::info('Plugin operation', ['data' => $data]);
\Log::error('Plugin error', ['error' => $e->getMessage()]);
```
### 2. Configuration Checking
### 2. 配置校验
```php
// Check required configuration
@@ -455,7 +453,7 @@ if (!$this->getConfig('required_key')) {
}
```
### 3. Development Mode
### 3. 开发模式
```php
if (config('app.debug')) {
@@ -463,37 +461,35 @@ if (config('app.debug')) {
}
```
## 📋 Plugin Lifecycle
## 插件生命周期
1. **Installation**: Validate configuration, register to database
2. **Enable**: Load plugin, register hooks and routes
3. **Running**: Handle requests, execute business logic
1. **安装**:校验配置并注册到数据库。
2. **启用**:加载插件并注册 hooks、路由、命令、调度。
3. **运行**:处理请求并执行业务逻辑。
## 🎉 Summary
## 阶段总结
Based on TelegramLogin plugin practical experience:
结合 TelegramLogin 插件的实践经验:
- **Simplicity**: Main class only 23 lines, focused on core functionality
- **Practicality**: Extends PluginController, convenient configuration access
- **Maintainability**: Clear directory structure, standard development patterns
- **Extensibility**: Hook-based architecture, easy to extend functionality
- **简洁**:主类短小、职责单一。
- **实用**:基于 `PluginController`,开发效率高。
- **可维护**:目录结构清晰,模式统一。
- **可扩展**:通过 hooks 可快速扩展业务。
Following this guide, you can quickly develop plugins with complete functionality and concise code! 🚀
## 插件 Artisan 命令完整指南
## 🖥️ Complete Plugin Artisan Commands Guide
### 功能亮点
### Feature Highlights
- **自动注册**:插件启用时自动注册 `Commands/` 下命令。
- **命名空间隔离**:各插件命令互不冲突。
- **类型安全**:支持 PHP 8.2 类型声明。
- **异常处理**:可统一错误输出与退出码。
- **配置集成**:命令中可读取插件配置。
- **交互支持**:支持输入、确认、选择等交互流程。
**Auto Registration**: Automatically register all commands in `Commands/` directory when plugin is enabled
**Namespace Isolation**: Each plugin's commands use independent namespaces
**Type Safety**: Support PHP 8.2 type declarations
**Error Handling**: Comprehensive exception handling and error messages
**Configuration Integration**: Commands can access plugin configuration
**Interaction Support**: Support user input and confirmation operations
### 真实案例
### Real Case Demonstrations
#### 1. Telegram Plugin Commands
#### 1. Telegram 插件命令
```bash
# Test Bot connection
@@ -506,7 +502,7 @@ php artisan telegram:test send --message="Hello World"
php artisan telegram:test info
```
#### 2. TelegramExtra Plugin Commands
#### 2. TelegramExtra 插件命令
```bash
# Show all statistics
@@ -519,7 +515,7 @@ php artisan telegram-extra:stats users
php artisan telegram-extra:stats users --format=json
```
#### 3. Example Plugin Commands
#### 3. Example 插件命令
```bash
# Basic usage
@@ -529,9 +525,9 @@ php artisan example:hello
php artisan example:hello Bear --message="Welcome!"
```
### Development Best Practices
### 命令开发规范
#### 1. Command Naming Conventions
#### 1. 命名约定
```php
// ✅ Recommended: Use plugin name as prefix
@@ -544,7 +540,7 @@ protected $signature = 'test {action}';
protected $signature = 'stats {type}';
```
#### 2. Error Handling Pattern
#### 2. 异常处理模式
```php
public function handle(): int
@@ -559,7 +555,7 @@ public function handle(): int
}
```
#### 3. User Interaction
#### 3. 交互能力
```php
// Get user input
@@ -575,7 +571,7 @@ if (!$this->confirm('Are you sure you want to execute this operation?')) {
$action = $this->choice('Choose operation', ['ping', 'send', 'info']);
```
#### 4. Configuration Access
#### 4. 配置访问
```php
// Access plugin configuration in commands
@@ -589,9 +585,9 @@ protected function getConfig(string $key, $default = null): mixed
}
```
### Advanced Usage
### 进阶用法
#### 1. Multi-Command Plugins
#### 1. 多命令插件
```php
// One plugin can have multiple commands
@@ -602,7 +598,7 @@ plugins/YourPlugin/Commands/
└── TestCommand.php # Test command
```
#### 2. Inter-Command Communication
#### 2. 命令间通信
```php
// Share data between commands through cache or database
@@ -610,7 +606,7 @@ Cache::put('plugin:backup:progress', $progress, 3600);
$progress = Cache::get('plugin:backup:progress');
```
#### 3. Scheduled Task Integration
#### 3. 与定时任务联动
```php
// Call commands in plugin's schedule method
@@ -621,9 +617,9 @@ public function schedule(Schedule $schedule): void
}
```
### Debugging Tips
### 命令调试建议
#### 1. Command Testing
#### 1. 命令测试
```bash
# View command help
@@ -636,7 +632,7 @@ php artisan your-plugin:command --verbose
php artisan your-plugin:command --debug
```
#### 2. Logging
#### 2. 命令日志
```php
// Log in commands
@@ -647,7 +643,7 @@ Log::info('Plugin command executed', [
]);
```
#### 3. Performance Monitoring
#### 3. 性能监控
```php
// Record command execution time
@@ -657,35 +653,35 @@ $endTime = microtime(true);
$this->info("Execution time: " . round(($endTime - $startTime) * 1000, 2) . "ms");
```
### Common Issues
### 常见问题
#### Q: Commands not showing in list?
#### Q: 命令没有出现在列表里?
A: Check if plugin is enabled and ensure `Commands/` directory exists and contains valid command classes.
A: 检查插件是否启用,并确认 `Commands/` 目录存在且命令类有效。
#### Q: Command execution failed?
#### Q: 命令执行失败?
A: Check if command class namespace is correct and ensure it extends `Illuminate\Console\Command`.
A: 检查命名空间是否正确,且类继承了 `Illuminate\Console\Command`
#### Q: How to access plugin configuration?
#### Q: 如何在命令中读取插件配置?
A: Get plugin instance through `PluginManager`, then call `getConfig()` method.
A: 通过 `PluginManager` 获取插件实例,再调用 `getConfig()`
#### Q: Can commands call other commands?
#### Q: 命令能否调用其他命令?
A: Yes, use `Artisan::call()` method to call other commands.
A: 可以,使用 `Artisan::call()`
```php
Artisan::call('other-plugin:command', ['arg' => 'value']);
```
### Summary
### 总结
The plugin command system provides powerful extension capabilities for XBoard:
插件命令系统为 XBoard 提供了强扩展能力:
- 🚀 **Development Efficiency**: Quickly create management commands
- 🔧 **Operational Convenience**: Automate daily operations
- 📊 **Monitoring Capability**: Real-time system status viewing
- 🛠️ **Debug Support**: Convenient problem troubleshooting tools
- **开发效率**:快速构建运维与管理命令
- **运维便利**:支持自动化日常操作
- **监控能力**:便于查看系统运行状态
- **调试支持**:可快速定位与排查问题
By properly using plugin commands, you can greatly improve system maintainability and user experience! 🎉
合理使用插件命令,可以显著提升系统可维护性和使用体验。