与其他模块集成.md 12 KB

任务模块与其他模块集成

1. 概述

任务模块作为开心农场系统的核心功能模块之一,需要与多个其他模块进行交互和集成。本文档详细说明任务模块与其他模块的集成方式、接口调用和事件通信机制。

2. 与用户模块集成

2.1 依赖关系

  • 任务模块需要获取用户基本信息
  • 任务模块需要验证用户等级和权限
  • 任务完成可能影响用户经验和等级

2.2 接口调用

2.2.1 获取用户信息

// 在TaskService中调用UserService
public function getAvailableTasks(int $userId, ?string $type = null): array
{
    // 获取用户信息,包括等级、VIP状态等
    $userInfo = UserService::getUserInfo($userId);
    
    // 根据用户等级筛选可用任务
    $tasks = $this->taskRepository->getAvailableTasks($userId, $type, $userInfo['level']);
    
    return $tasks;
}

2.2.2 验证用户等级

// 在TaskLogic中验证用户等级
public function canAcceptTask(int $userId, int $taskId): bool
{
    $task = $this->taskRepository->find($taskId);
    $userInfo = UserService::getUserInfo($userId);
    
    if ($userInfo['level'] < $task->level_required) {
        return false;
    }
    
    return true;
}

2.3 事件通信

2.3.1 监听用户等级变更事件

// 在TaskModule的事件监听器中
public function handleUserLevelUp(UserLevelUpEvent $event): void
{
    // 当用户升级时,检查是否有新的任务可以解锁
    $userId = $event->userId;
    $newLevel = $event->newLevel;
    
    // 解锁新等级的任务
    TaskService::unlockTasksByLevel($userId, $newLevel);
}

3. 与物品模块集成

3.1 依赖关系

  • 任务完成后需要发放物品奖励
  • 某些任务需要验证用户物品使用情况
  • 物品使用可能触发任务进度更新

3.2 接口调用

3.2.1 发放任务奖励

// 在TaskLogic中处理任务奖励
public function processTaskReward(int $userId, int $taskId): array
{
    $task = $this->taskRepository->find($taskId);
    $rewards = json_decode($task->rewards, true);
    
    $result = [];
    
    // 开始事务
    DB::beginTransaction();
    try {
        foreach ($rewards['items'] as $reward) {
            // 调用物品模块服务添加物品
            $itemResult = ItemService::addItem(
                $userId,
                $reward['item_id'],
                $reward['quantity'],
                [
                    'source_type' => 'task_reward',
                    'source_id' => $taskId,
                    'details' => ['task_name' => $task->name]
                ]
            );
            
            $result[] = [
                'item_id' => $reward['item_id'],
                'quantity' => $reward['quantity'],
                'success' => $itemResult['success']
            ];
        }
        
        DB::commit();
        return $result;
    } catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}

3.2.2 验证物品使用情况

// 在TaskLogic中验证物品使用任务
public function validateUseItemTask(int $userId, int $taskId, int $itemId, int $quantity): bool
{
    $task = $this->taskRepository->find($taskId);
    $targetParams = json_decode($task->target_params, true);
    
    // 检查是否是目标物品
    if (isset($targetParams['item_ids']) && !in_array($itemId, $targetParams['item_ids'])) {
        return false;
    }
    
    return true;
}

3.3 事件通信

3.3.1 监听物品使用事件

// 在TaskModule的事件监听器中
public function handleItemUsed(ItemUsedEvent $event): void
{
    // 当物品被使用时,更新相关任务进度
    $userId = $event->userId;
    $itemId = $event->itemId;
    $quantity = $event->quantity;
    
    // 更新使用物品类型的任务进度
    TaskService::updateTaskProgress(
        $userId,
        TARGET_TYPE::USE_ITEM->value,
        ['item_id' => $itemId],
        $quantity
    );
}

4. 与农场模块集成

4.1 依赖关系

  • 农场活动(种植、收获等)可能触发任务进度更新
  • 任务可能要求特定农场操作
  • 任务奖励可能影响农场状态

4.2 接口调用

4.2.1 获取农场信息

// 在TaskService中获取农场信息
public function getPlantingTasks(int $userId): array
{
    // 获取用户农场信息
    $farmInfo = FarmService::getUserFarmInfo($userId);
    
    // 根据农场状态筛选适合的种植任务
    $tasks = $this->taskRepository->getTasksByTargetType(
        $userId,
        TARGET_TYPE::PLANT->value,
        ['house_level' => $farmInfo['house_level']]
    );
    
    return $tasks;
}

4.3 事件通信

4.3.1 监听种植事件

// 在TaskModule的事件监听器中
public function handleCropPlanted(CropPlantedEvent $event): void
{
    // 当作物被种植时,更新相关任务进度
    $userId = $event->userId;
    $seedId = $event->seedId;
    $landId = $event->landId;
    
    // 更新种植任务进度
    TaskService::updateTaskProgress(
        $userId,
        TARGET_TYPE::PLANT->value,
        ['seed_id' => $seedId, 'land_id' => $landId],
        1
    );
}

4.3.2 监听收获事件

// 在TaskModule的事件监听器中
public function handleCropHarvested(CropHarvestedEvent $event): void
{
    // 当作物被收获时,更新相关任务进度
    $userId = $event->userId;
    $cropId = $event->cropId;
    $quantity = $event->quantity;
    
    // 更新收获任务进度
    TaskService::updateTaskProgress(
        $userId,
        TARGET_TYPE::HARVEST->value,
        ['crop_id' => $cropId],
        $quantity
    );
}

5. 与团队模块集成

5.1 依赖关系

  • 任务完成后需要计算团队收益分成
  • 团队任务需要多人协作完成
  • 推荐任务与团队发展相关

5.2 接口调用

5.2.1 记录任务完成收益

// 在TaskService中记录任务完成收益
public function completeTask(int $userId, int $taskId): array
{
    $result = $this->taskLogic->completeTask($userId, $taskId);
    
    if ($result['success']) {
        // 记录团队收益
        foreach ($result['rewards'] as $reward) {
            if (isset($reward['item_id']) && isset($reward['quantity'])) {
                TeamProfitService::recordTaskCompleteProfit(
                    $userId,
                    $taskId,
                    $reward['item_id'],
                    $reward['quantity']
                );
            }
        }
    }
    
    return $result;
}

5.2.2 创建团队任务

// 在TeamTaskService中创建团队任务
public function createTeamTask(int $creatorId, array $taskData): array
{
    // 验证创建者是否是达人
    $talentInfo = $this->talentRepository->getByUserId($creatorId);
    if (!$talentInfo || $talentInfo->talent_level < 3) {
        throw new TalentException("只有高级及以上达人才能创建团队任务");
    }
    
    // 创建基础任务
    $taskId = TaskService::createTask([
        'name' => $taskData['name'],
        'description' => $taskData['description'],
        'type' => TASK_TYPE::TEAM->value,
        'target_type' => $taskData['target_type'],
        'target_params' => $taskData['target_params'],
        'target_count' => $taskData['target_count'],
        'rewards' => $taskData['rewards'],
        'time_limit' => $taskData['time_limit'] ?? 604800, // 默认7天
        'is_active' => true
    ]);
    
    // 创建团队任务记录
    $teamTask = $this->teamTaskRepository->create([
        'task_id' => $taskId,
        'creator_id' => $creatorId,
        'team_id' => $taskData['team_id'],
        'min_participants' => $taskData['min_participants'] ?? 1,
        'max_participants' => $taskData['max_participants'] ?? 0,
        'status' => 1, // 活跃状态
        'expire_at' => now()->addSeconds($taskData['time_limit'] ?? 604800)
    ]);
    
    return [
        'success' => true,
        'task_id' => $taskId,
        'team_task_id' => $teamTask->id
    ];
}

5.3 事件通信

5.3.1 监听团队成员变更事件

// 在TaskModule的事件监听器中
public function handleTeamMemberAdded(TeamMemberAddedEvent $event): void
{
    // 当团队添加新成员时,更新相关推荐任务进度
    $userId = $event->referrerId; // 推荐人ID
    $newMemberId = $event->newMemberId;
    
    // 更新推荐任务进度
    TaskService::updateTaskProgress(
        $userId,
        TARGET_TYPE::INVITE->value,
        [],
        1
    );
}

6. 与宠物模块集成

6.1 依赖关系

  • 宠物相关活动可能触发任务进度更新
  • 任务可能要求特定宠物操作
  • 任务奖励可能包含宠物相关物品

6.2 接口调用

6.2.1 验证宠物状态

// 在TaskLogic中验证宠物任务
public function validatePetTask(int $userId, int $taskId): bool
{
    $task = $this->taskRepository->find($taskId);
    $targetParams = json_decode($task->target_params, true);
    
    // 获取用户宠物信息
    $petInfo = PetService::getUserPetInfo($userId);
    
    // 检查宠物等级要求
    if (isset($targetParams['min_pet_level']) && $petInfo['level'] < $targetParams['min_pet_level']) {
        return false;
    }
    
    return true;
}

6.3 事件通信

6.3.1 监听宠物喂养事件

// 在TaskModule的事件监听器中
public function handlePetFed(PetFedEvent $event): void
{
    // 当宠物被喂养时,更新相关任务进度
    $userId = $event->userId;
    $petId = $event->petId;
    $foodId = $event->foodId;
    
    // 更新喂养宠物任务进度
    TaskService::updateTaskProgress(
        $userId,
        TARGET_TYPE::FEED_PET->value,
        ['pet_id' => $petId, 'food_id' => $foodId],
        1
    );
}

7. 与通知模块集成

7.1 依赖关系

  • 任务状态变更需要发送通知
  • 任务即将过期需要提醒用户
  • 新任务可用时需要通知用户

7.2 接口调用

7.2.1 发送任务完成通知

// 在TaskService中发送任务完成通知
public function completeTask(int $userId, int $taskId): array
{
    $result = $this->taskLogic->completeTask($userId, $taskId);
    
    if ($result['success']) {
        // 发送任务完成通知
        NotificationService::send(
            $userId,
            'task_completed',
            [
                'task_id' => $taskId,
                'task_name' => $result['task_name'],
                'rewards' => $result['rewards']
            ]
        );
    }
    
    return $result;
}

7.2.2 发送任务过期提醒

// 在TaskService中发送任务过期提醒
public function sendExpirationReminders(): int
{
    // 获取即将过期的任务(24小时内)
    $expiringTasks = $this->taskRepository->getExpiringTasks(86400);
    
    $count = 0;
    foreach ($expiringTasks as $task) {
        // 发送过期提醒通知
        NotificationService::send(
            $task->user_id,
            'task_expiring',
            [
                'task_id' => $task->task_id,
                'task_name' => $task->name,
                'expire_at' => $task->expire_at,
                'time_remaining' => strtotime($task->expire_at) - time()
            ]
        );
        $count++;
    }
    
    return $count;
}

8. 集成最佳实践

8.1 使用事件驱动架构

  • 使用事件和监听器实现模块间的松耦合通信
  • 避免直接依赖,减少模块间的耦合度
  • 使用事件队列处理异步任务,提高系统响应性能

8.2 统一接口规范

  • 定义清晰的服务接口,隐藏内部实现细节
  • 使用数据传输对象(DTO)进行跨模块数据交换
  • 统一错误处理和返回格式

8.3 事务管理

  • 跨模块操作使用数据库事务确保一致性
  • 关键操作添加重试机制
  • 使用分布式事务处理复杂场景

8.4 性能优化

  • 使用缓存减少跨模块调用频率
  • 批量处理任务进度更新
  • 异步处理非关键路径操作

8.5 安全考虑

  • 跨模块调用进行权限验证
  • 敏感操作记录详细日志
  • 防止数据泄露和越权访问

9. 集成测试策略

9.1 单元测试

  • 使用模拟对象(Mock)测试模块间接口
  • 验证各模块独立功能正确性

9.2 集成测试

  • 测试模块间实际交互
  • 验证事件触发和处理机制
  • 测试跨模块事务处理

9.3 端到端测试

  • 模拟真实用户场景
  • 验证完整业务流程
  • 测试性能和并发处理能力