改进FertilizerHandler处理施肥操作请求,在验证后获取作物ID/土地ID,调用服务层传入作物ID,作物ID直接用于处理施肥效果。
原有的FertilizerHandler在验证通过后,仍然使用用户ID和土地ID调用服务层,服务层需要重新查询作物信息。这种设计存在以下问题:
// 从验证结果中获取数据,避免重复查询
$cropGrowthTime = $validation->crop_growth_time;
$crop = $validation->crop; // 从验证结果中获取作物对象
$cropId = $crop->id; // 获取作物ID
Log::info('FertilizerHandler: 验证通过,获取到作物信息', [
'user_id' => $userId,
'land_id' => $landId,
'crop_id' => $cropId,
'crop_growth_time' => $cropGrowthTime,
]);
// 使用肥料(直接传入作物ID)
$result = CropService::useFertilizer($cropId, $cropGrowthTime);
/**
* 使用化肥(通过作物ID)
*
* @param int $cropId 作物ID
* @param int $cropGrowthTime 减少的生长时间(秒)
* @return Res
*/
public static function useFertilizer(int $cropId, int $cropGrowthTime): Res
{
try {
$cropLogic = new CropLogic();
return $cropLogic->useFertilizerByCropId($cropId, $cropGrowthTime);
} catch (\Exception $e) {
Log::error('使用化肥失败', [
'crop_id' => $cropId,
'crop_growth_time' => $cropGrowthTime,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return Res::error('使用化肥失败');
}
}
/**
* 使用化肥(通过作物ID)
*
* @param int $cropId 作物ID
* @param int $cropGrowthTime 减少的生长时间(秒)
* @return Res
*/
public function useFertilizerByCropId(int $cropId, int $cropGrowthTime): Res
{
try {
Helper::check_tr();
// 获取作物信息(防错误机制:确保作物存在)
$crop = FarmCrop::find($cropId);
if (!$crop) {
throw new \Exception('作物不存在');
}
// 防错误机制:基本状态检查,避免意外执行
if ($crop->fertilized) {
throw new \Exception('作物已施肥');
}
// 更新作物信息和减少生长时间
$crop->fertilized = true;
// ... 施肥逻辑处理
return Res::success('', [
'crop_id' => $crop->id,
]);
} catch (\Exception $e) {
return Res::error('使用化肥失败');
}
}
通过Protobuf请求测试验证改进效果:
[2025-05-27T14:46:32.176140+08:00] laravel.INFO: FertilizerHandler: 验证通过,获取到作物信息 {"user_id":10001,"land_id":13,"crop_id":36,"crop_growth_time":360000}
[2025-05-27T14:46:32.232431+08:00] laravel.INFO: 使用化肥成功 {"crop_id":36,"user_id":10001,"land_id":13,"growth_stage":{"App\\Module\\Farm\\Enums\\GROWTH_STAGE":30},"stage_end_time":"2025-05-27T14:46:32+08:00"}
[2025-05-27T14:46:32.359938+08:00] laravel.INFO: 施肥操作成功 {"user_id":10001,"land_id":13,"item_id":21,"crop_id":36,"crop_growth_time":360000}
改进FertilizerHandler:验证后获取作物ID并传递给服务层进行施肥效果处理
- 修改FertilizerHandler从验证结果中获取作物ID
- 修改CropService::useFertilizer方法接受作物ID参数
- 新增CropLogic::useFertilizerByCropId方法直接使用作物ID处理施肥效果
- 保留兼容性方法useFertilizerByLandId
- 优化日志记录,包含作物ID信息
- 通过测试验证改进效果
2025-05-27 15:30