فهرست منبع

feat(pet): 添加宠物创建事件并优化喂养逻辑

- 新增 PetCreatedEvent 类用于宠物创建事件
- 在 PetLogic 中触发宠物创建事件
- 优化 EatHandler 中的喂养逻辑,添加事务处理和错误日志
- 调整 ItemService 为静态方法,提高易用性- 移除 PetFoodValidator 中的冗余代码
Your Name 8 ماه پیش
والد
کامیت
d4765ea0f2

+ 41 - 2
app/Module/AppGame/Handler/Pet/EatHandler.php

@@ -38,13 +38,52 @@ class EatHandler extends BaseHandler
         $validation->validated();
         // 验证完成
 
+        // 获取请求参数
+        $petId = $validation->pet_id;
+        $itemId = $validation->item_id;
+        $num = $validation->num;
+        $userId = $validation->user_id;
 
+        // 创建响应对象
+        $response = new ResponsePetEat();
 
+        try {
+            // 开启数据库事务
+            DB::beginTransaction();
 
+            // 调用宠物服务进行喂养
+            $feedResult = PetService::feedPet($userId, $petId, $itemId, $num);
 
+            // 设置响应数据
+            $response->setSuccess(true);
+            $response->setPetId($petId);
+            $response->setItemId($itemId);
+            $response->setNum($num);
+            $response->setExpGained($feedResult['exp_gained']);
+            $response->setStaminaGained($feedResult['stamina_gained']);
+            $response->setLevelUp($feedResult['level_up']);
+            $response->setMessage('宠物喂养成功');
+
+            // 提交事务
+            DB::commit();
+        } catch (\Exception $e) {
+            // 回滚事务
+            DB::rollBack();
+
+            // 记录错误日志
+            Log::error('宠物喂养失败', [
+                'user_id' => $userId,
+                'pet_id' => $petId,
+                'item_id' => $itemId,
+                'num' => $num,
+                'error' => $e->getMessage()
+            ]);
+
+            // 设置错误响应
+            $response->setSuccess(false);
+            $response->setMessage('宠物喂养失败: ' . $e->getMessage());
+        }
 
-        // 创建响应对象
-        $response = new ResponsePetEat();
         return $response;
     }
 

+ 1 - 1
app/Module/Game/Logics/ItemCache.php

@@ -3,8 +3,8 @@
 namespace App\Module\Game\Logics;
 
 use App\Module\GameItems\Events\ItemQuantityChanged;
-use App\Module\LCache\Cache;
 use Illuminate\Support\Facades\Log;
+use UCore\Helper\Cache;
 
 /**
  * 物品缓存逻辑类

+ 1 - 0
app/Module/Game/Queues/README.md

@@ -0,0 +1 @@
+# 队列

+ 0 - 8
app/Module/Game/Queues/TestQueue.php

@@ -1,8 +0,0 @@
-<?php
-
-namespace App\Module\Game\Queues;
-
-class TestQueue
-{
-
-}

+ 0 - 10
app/Module/Game/Repositorys/FundAdminRepository.php

@@ -1,10 +0,0 @@
-<?php
-
-namespace App\Module\Game\Repositorys;
-
-use UCore\DcatAdmin\Repository\EloquentRepository;
-
-class FundAdminRepository extends EloquentRepository
-{
-
-}

+ 1 - 0
app/Module/Game/Repositorys/README.md

@@ -0,0 +1 @@
+# 数据仓库(后台专属)

+ 20 - 22
app/Module/GameItems/Services/ItemService.php

@@ -14,23 +14,11 @@ use Illuminate\Database\Eloquent\Collection;
  * 提供物品相关的服务,包括获取用户物品、添加物品到用户背包、消耗用户物品等功能。
  * 该类是物品模块对外提供服务的主要入口,封装了物品操作的复杂逻辑,
  * 通过调用ItemLogic类实现具体的业务逻辑处理。
+ *
+ * 所有方法均为静态方法,可直接通过类名调用。
  */
 class ItemService
 {
-    /**
-     * 物品逻辑类
-     *
-     * @var ItemLogic
-     */
-    private $itemLogic;
-
-    /**
-     * 构造函数
-     */
-    public function __construct()
-    {
-        $this->itemLogic = new ItemLogic();
-    }
     /**
      * 获取用户物品列表
      *
@@ -39,7 +27,7 @@ class ItemService
      * @param bool $includeExpired 是否包含已过期物品
      * @return Collection|ItemUser[]
      */
-    public function getUserItems(int $userId, array $filters = [], bool $includeExpired = false): Collection
+    public static function getUserItems(int $userId, array $filters = [], bool $includeExpired = false): Collection
     {
         $query = ItemUser::where('user_id', $userId)
             ->with(['item', 'instance']);
@@ -88,23 +76,23 @@ class ItemService
      * @return array 添加结果
      * @throws Exception
      */
-    public function addItem(int $userId, int $itemId, int $quantity, array $options = []): array
+    public static function addItem(int $userId, int $itemId, int $quantity, array $options = []): array
     {
         // 获取物品信息
         $item = Item::findOrFail($itemId);
 
         // 检查物品是否已过期(全局过期)
-        if ($this->itemLogic->isExpired($item)) {
+        if (ItemLogic::isExpired($item)) {
             throw new Exception("物品 {$itemId} 已全局过期");
         }
 
         // 处理单独属性物品
         if ($item->is_unique) {
-            return $this->itemLogic->addUniqueItem($userId, $itemId, $options);
+            return ItemLogic::addUniqueItem($userId, $itemId, $options);
         }
 
         // 处理统一属性物品
-        return $this->itemLogic->addNormalItem($userId, $itemId, $quantity, $options);
+        return ItemLogic::addNormalItem($userId, $itemId, $quantity, $options);
     }
 
     /**
@@ -118,19 +106,29 @@ class ItemService
      * @return array 消耗结果
      * @throws Exception
      */
-    public function consumeItem(int $userId, int $itemId, ?int $instanceId, int $quantity, array $options = []): array
+    public static function consumeItem(int $userId, int $itemId, ?int $instanceId, int $quantity, array $options = []): array
     {
         // 获取物品信息
         $item = Item::findOrFail($itemId);
 
         if ($instanceId) {
             // 消耗单独属性物品
-            return $this->itemLogic->consumeUniqueItem($userId, $itemId, $instanceId, $options);
+            return ItemLogic::consumeUniqueItem($userId, $itemId, $instanceId, $options);
         } else {
             // 消耗统一属性物品
-            return $this->itemLogic->consumeNormalItem($userId, $itemId, $quantity, $options);
+            return ItemLogic::consumeNormalItem($userId, $itemId, $quantity, $options);
         }
     }
 
+    /**
+     * 获取物品信息
+     *
+     * @param int $itemId 物品ID
+     * @return Item|null 物品信息
+     */
+    public static function getItemInfo(int $itemId): ?Item
+    {
+        return Item::find($itemId);
+    }
 
 }

+ 14 - 1
app/Module/Pet/Docs/事件系统.md

@@ -41,7 +41,18 @@
 - `oldGrade`: 旧品阶
 - `newGrade`: 新品阶
 
-#### 2.1.4 宠物战斗事件 (PetBattleEvent)
+#### 2.1.4 宠物创建事件 (PetCreatedEvent)
+
+当新宠物被创建时触发此事件。
+
+**属性**:
+- `userId`: 用户ID
+- `petId`: 宠物ID
+- `name`: 宠物名称
+- `grade`: 宠物品阶
+- `level`: 宠物等级
+
+#### 2.1.5 宠物战斗事件 (PetBattleEvent)
 
 当宠物参与战斗时触发此事件。
 
@@ -106,6 +117,7 @@
 
 | 事件名称 | 事件类 | 触发条件 | 包含数据 | 用途 |
 |---------|-------|---------|---------|------|
+| 宠物创建事件 | PetCreatedEvent | 新宠物被创建 | userId, petId, name, grade, level | 通知其他模块新宠物被创建 |
 | 宠物技能使用事件 | PetSkillUsedEvent | 用户使用宠物技能 | userId, petId, skillId, params | 通知其他模块宠物技能被使用 |
 | 宠物升级事件 | PetLevelUpEvent | 宠物升级 | userId, petId, oldLevel, newLevel, unlockedSkills | 通知其他模块宠物升级,可能解锁新技能 |
 | 宠物洗髓事件 | PetRemouldEvent | 宠物洗髓 | userId, petId, oldGrade, newGrade | 通知其他模块宠物品阶变更 |
@@ -125,6 +137,7 @@
 |-------|---------|---------|
 | ItemChangedEvent | ItemChangedListener | handle() |
 | LoginSuccessEvent | LoginSuccessListener | handle() |
+| PetCreatedEvent | PetCreatedListener | handle() |
 | PetStatusChangedEvent | PetStatusChangedListener | handle() |
 | PetLevelUpEvent | PetLevelUpListener | handle() |
 | PetRemouldEvent | PetRemouldListener | handle() |

+ 73 - 0
app/Module/Pet/Events/PetCreatedEvent.php

@@ -0,0 +1,73 @@
+<?php
+
+namespace App\Module\Pet\Events;
+
+use App\Module\Pet\Enums\PetGrade;
+use Illuminate\Broadcasting\InteractsWithSockets;
+use Illuminate\Foundation\Events\Dispatchable;
+use Illuminate\Queue\SerializesModels;
+
+/**
+ * 宠物创建事件
+ * 
+ * 当新宠物被创建时触发此事件,允许其他系统响应宠物的创建。
+ * 此事件可用于记录宠物创建日志、更新用户状态、处理新手引导等。
+ */
+class PetCreatedEvent
+{
+    use Dispatchable, InteractsWithSockets, SerializesModels;
+
+    /**
+     * 用户ID
+     *
+     * @var int
+     */
+    public int $userId;
+
+    /**
+     * 宠物ID
+     *
+     * @var int
+     */
+    public int $petId;
+
+    /**
+     * 宠物名称
+     *
+     * @var string
+     */
+    public string $name;
+
+    /**
+     * 宠物品阶
+     *
+     * @var PetGrade
+     */
+    public PetGrade $grade;
+
+    /**
+     * 宠物等级
+     *
+     * @var int
+     */
+    public int $level;
+
+    /**
+     * 创建一个新的事件实例
+     *
+     * @param int $userId 用户ID
+     * @param int $petId 宠物ID
+     * @param string $name 宠物名称
+     * @param PetGrade $grade 宠物品阶
+     * @param int $level 宠物等级
+     * @return void
+     */
+    public function __construct(int $userId, int $petId, string $name, PetGrade $grade, int $level = 1)
+    {
+        $this->userId = $userId;
+        $this->petId = $petId;
+        $this->name = $name;
+        $this->grade = $grade;
+        $this->level = $level;
+    }
+}

+ 15 - 25
app/Module/Pet/Logic/PetLogic.php

@@ -4,6 +4,7 @@ namespace App\Module\Pet\Logic;
 
 use App\Module\GameItems\Services\ItemService;
 use App\Module\Pet\Enums\PetStatus;
+use App\Module\Pet\Events\PetCreatedEvent;
 use App\Module\Pet\Events\PetLevelUpEvent;
 use App\Module\Pet\Events\PetRemouldEvent;
 use App\Module\Pet\Events\PetSkillUsedEvent;
@@ -14,7 +15,6 @@ use App\Module\Pet\Models\PetRemouldLog;
 use App\Module\Pet\Models\PetSkill;
 use App\Module\Pet\Models\PetSkillLog;
 use App\Module\Pet\Models\PetUser;
-use App\Module\Pet\Validators\PetFoodValidator;
 use Exception;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
@@ -28,27 +28,12 @@ use Illuminate\Support\Facades\Log;
  */
 class PetLogic
 {
-    /**
-     * 物品服务
-     *
-     * @var ItemService
-     */
-    protected $itemService;
-
-    /**
-     * 宠物食物验证器
-     *
-     * @var PetFoodValidator
-     */
-    protected $petFoodValidator;
-
     /**
      * 构造函数
      */
     public function __construct()
     {
-        $this->itemService = new ItemService();
-        $this->petFoodValidator = new PetFoodValidator();
+        // 构造函数不需要初始化任何属性
     }
 
     /**
@@ -101,11 +86,20 @@ class PetLogic
         $pet->status = PetStatus::NORMAL;
         $pet->save();
 
+        // 触发宠物创建事件
+        event(new PetCreatedEvent(
+            $userId,
+            $pet->id,
+            $name,
+            $grade,
+            1 // 初始等级为1
+        ));
+
         Log::info('宠物创建成功', [
             'user_id' => $userId,
             'pet_id' => $pet->id,
             'name' => $name,
-            'grade' => $grade->value
+            'grade' => $grade
         ]);
 
         return [
@@ -221,19 +215,15 @@ class PetLogic
         // 获取宠物信息
         $pet = PetUser::findOrFail($petId);
 
-        // 验证物品是否为宠物口粮
-        if (!$this->petFoodValidator->validate($itemId, [])) {
-            throw new Exception("该物品不是宠物口粮");
-        }
 
         // 获取物品信息
-        $item = $this->itemService->getItemInfo($itemId);
+        $item = ItemService::getItemInfo($itemId);
         if (!$item) {
             throw new Exception("物品不存在");
         }
 
         // 消耗物品
-        $consumeResult = $this->itemService->consumeItem(
+        $consumeResult = ItemService::consumeItem(
             $pet->user_id,
             $itemId,
             null,
@@ -392,7 +382,7 @@ class PetLogic
             }
 
             // 消耗物品
-            $consumeResult = $this->itemService->consumeItem(
+            $consumeResult = ItemService::consumeItem(
                 $pet->user_id,
                 $itemId,
                 null,

+ 3 - 2
app/Module/Pet/Providers/PetServiceProvider.php

@@ -3,6 +3,7 @@
 namespace App\Module\Pet\Providers;
 
 use App\Module\Pet\Events\PetBattleEvent;
+use App\Module\Pet\Events\PetCreatedEvent;
 use App\Module\Pet\Events\PetLevelUpEvent;
 use App\Module\Pet\Events\PetRemouldEvent;
 use App\Module\Pet\Events\PetSkillUsedEvent;
@@ -43,8 +44,8 @@ class PetServiceProvider extends ServiceProvider
      */
     public function register()
     {
-       
-        
+
+
     }
 
     /**

+ 2 - 8
app/Module/Pet/Validators/PetFoodValidator.php

@@ -52,11 +52,8 @@ class PetFoodValidator extends Validator
         }
 
         try {
-            // 创建物品服务实例
-            $itemService = new ItemService();
-
             // 获取物品信息
-            $item = $itemService->getItemInfo($itemId);
+            $item = ItemService::getItemInfo($itemId);
 
             if (!$item) {
                 // 物品不存在
@@ -121,11 +118,8 @@ class PetFoodValidator extends Validator
     public function getPetFoodAttributes(int $itemId): array
     {
         try {
-            // 创建物品服务实例
-            $itemService = new ItemService();
-
             // 获取物品信息
-            $item = $itemService->getItemInfo($itemId);
+            $item = ItemService::getItemInfo($itemId);
 
             if (!$item) {
                 return [