任务时间: 2025年05月26日 17:38
任务类型: 代码优化
涉及模块: AppGame, Farm, GameItems
按照PesticideHandler模式优化FertilizerHandler:先验证再执行操作,创建必要的Validation和Validator类,在事务外进行验证。
文件: app/Module/Farm/Validations/FertilizerValidation.php
功能:
验证规则:
文件: app/Module/Farm/Validators/FertilizerItemValidator.php
功能:
验证逻辑:
// 检查物品是否存在
$item = Item::find($value);
// 获取肥料属性
$cropGrowthTime = ItemService::getItemNumericAttribute($value, 'crop_growth_time', 0);
// 验证是否为有效肥料(crop_growth_time > 0)
if ($cropGrowthTime <= 0) {
return false;
}
文件: app/Module/Farm/Validators/FertilizerUsageValidator.php
功能:
验证逻辑:
// 检查土地状态是否为种植中
if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
return false;
}
// 检查作物生长阶段
if (!GROWTH_STAGE::canUseFertilizer($crop->growth_stage)) {
return false;
}
// 检查是否已经使用过肥料
if ($crop->fertilized) {
return false;
}
文件: app/Module/AppGame/Handler/Land/FertilizerHandler.php
主要变更:
关键代码:
// 使用FertilizerValidation进行数据验证
$validation = new FertilizerValidation();
if (!$validation->validate($validationData)) {
throw new LogicException($validation->getErrors());
}
// 从验证结果中获取数据,避免重复查询
$cropGrowthTime = $validation->crop_growth_time;
// 在事务中执行操作
DB::beginTransaction();
$result = CropService::useFertilizer($userId, $landId, $cropGrowthTime);
文件: app/Module/Farm/Logics/CropLogic.php
主要变更:
关键代码:
// 防错误机制:基本状态检查,避免意外执行
if ($land->status !== LAND_STATUS::PLANTING->valueInt()) {
Log::warning('土地状态异常,但继续执行施肥', [
'land_id' => $landId,
'expected_status' => LAND_STATUS::PLANTING->valueInt(),
'actual_status' => $land->status
]);
}
if ($crop->fertilized) {
Log::warning('作物已施肥,但继续执行', [
'crop_id' => $crop->id,
'fertilized' => $crop->fertilized
]);
}
UCore\Validator 作为基类validate(mixed $value, array $data): bool 方法$this->args 获取参数配置$this->validation 设置验证结果[
'land_id', LandOwnershipValidator::class, 'args' => ['user_id', 'land'],
'msg' => '土地不存在或不属于当前用户'
],
[
'item_id', FertilizerItemValidator::class, 'args' => ['fertilizer_item', 'crop_growth_time'],
'msg' => '该物品不是有效的肥料'
]
本次优化成功实现了FertilizerHandler的验证逻辑分离,提高了代码的可维护性和性能。通过在事务外进行验证,减少了事务时间;通过防错误机制,确保了系统的稳定性。整体架构与PesticideHandler保持一致,提高了代码的一致性。