根据要求,我们对神像系统进行了两个主要优化:
NumericAttributesCast 增加神像时间属性OpenHandler,参考 PesticideHandler 的实现方式文件: app/Module/GameItems/Casts/NumericAttributesCast.php
新增属性:
/**
* 神像时间(秒),用以标识该物品可以开启神像
*
* @var int $god_duration_seconds
*/
public int $god_duration_seconds = 0;
作用:
文件: app/Module/Farm/Validations/GodActivationValidation.php
功能:
文件: app/Module/Farm/Validators/GodActivationValidator.php
验证内容:
文件: app/Module/AppGame/Handler/God/OpenHandler.php
优化前的问题:
handle 方法中优化后的改进:
智能物品查找 (findGodItem 方法):
private function findGodItem(int $userId): int
{
// 获取用户所有物品
$userItems = ItemService::getUserItems($userId);
foreach ($userItems as $userItem) {
// 检查物品是否具有神像时间属性
$godDuration = ItemService::getItemNumericAttribute($userItem->itemId, 'god_duration_seconds');
if ($godDuration > 0) {
return $userItem->itemId;
}
}
throw new LogicException("您没有神像物品");
}
动态时间计算 (activateGodBuff 方法):
// 获取物品的神像时间属性
$godDurationSeconds = ItemService::getItemNumericAttribute($itemId, 'god_duration_seconds');
$durationHours = $godDurationSeconds > 0 ? ceil($godDurationSeconds / 3600) : 24; // 转换为小时,默认24小时
优化前:
开启事务 → 验证 → 业务逻辑 → 提交/回滚
优化后:
验证 → 开启事务 → 业务逻辑 → 提交/回滚
| 异常类型 | 处理方式 | HTTP状态码 | 说明 |
|---|---|---|---|
| ValidateException | 验证失败,无需回滚 | 400 | 参数验证失败 |
| LogicException | 业务异常,需要回滚 | 400 | 业务逻辑错误 |
| Exception | 系统异常,需要回滚 | 500 | 系统级错误 |
优化前: 硬编码物品ID映射
$godItemId = 3000 + $godId; // 假设神像物品ID为3001-3004
优化后: 基于属性的动态识别
// 检查物品是否具有神像时间属性
$godDuration = ItemService::getItemNumericAttribute($userItem->itemId, 'god_duration_seconds');
if ($godDuration > 0) {
return $userItem->itemId; // 找到神像物品
}
在物品配置中设置 numeric_attributes:
{
"god_duration_seconds": 86400
}
86400 = 24小时3600 = 1小时0 = 不是神像物品// 激活神像请求
{
"god_id": 1 // 1=丰收之神, 2=雨露之神, 3=屠草之神, 4=拭虫之神
}
// 成功响应
{
"code": 0,
"msg": "神像激活成功",
"last_data": {
"gods": [
{
"id": 1,
"status": true,
"vaid_time": 1716537600 // 过期时间戳
}
]
}
}
测试文件: tests/Unit/GodActivationTest.php
测试内容:
god_duration_seconds 属性,默认使用24小时通过这次优化,神像系统变得更加:
这些改进为神像系统的未来扩展奠定了良好的基础,同时保持了与现有系统的兼容性。