GenerateItemsJsonCommand.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Module\GameItems\Commands;
  3. use App\Module\Game\DCache\ItemJsonConfig;
  4. use App\Module\Game\Services\JsonConfigService;
  5. use Illuminate\Console\Command;
  6. use App\Module\GameItems\Models\Item;
  7. use Illuminate\Support\Facades\File;
  8. use Illuminate\Support\Facades\Log;
  9. /**
  10. * 生成物品配置表JSON数据命令
  11. *
  12. * 该命令用于从数据库中的物品表生成物品JSON数据文件,供客户端使用。
  13. * 生成的JSON文件包含物品的基本信息,如ID、名称、描述、售价和显示属性等。
  14. * 该命令通常在物品数据更新后运行,以确保客户端获取最新的物品数据。
  15. */
  16. class GenerateItemsJsonCommand extends Command
  17. {
  18. /**
  19. * 命令名称和签名
  20. *
  21. * @var string
  22. */
  23. protected $signature = 'gameitems:generate-json';
  24. /**
  25. * 命令描述
  26. *
  27. * @var string
  28. */
  29. protected $description = 'Generate items.json from Item table';
  30. /**
  31. * 执行命令
  32. */
  33. /**
  34. * 生成物品JSON数据
  35. */
  36. public static function generateJson()
  37. {
  38. try {
  39. // 查询Item表中的数据
  40. $items = Item::query()
  41. ->select([
  42. 'id',
  43. 'name',
  44. 'description',
  45. 'sell_price',
  46. 'display_attributes'
  47. ])
  48. ->get()
  49. ->map(function ($item) {
  50. return [
  51. 'id' => $item->id,
  52. 'name' => $item->name,
  53. 'description' => $item->description,
  54. 'sell_price' => $item->sell_price,
  55. 'display_attributes' => $item->display_attributes
  56. ];
  57. })
  58. ->toArray();
  59. // 准备完整数据,包含生成时间
  60. $data = [
  61. 'generated_at' => now()->toDateTimeString(),
  62. 'items' => $items
  63. ];
  64. return $data;
  65. } catch (\Exception $e) {
  66. Log::error('Generate items.json failed: ' . $e->getMessage());
  67. return false;
  68. }
  69. }
  70. public function handle()
  71. {
  72. if (ItemJsonConfig::getData([], true)) {
  73. $this->info('Successfully generated items.json with timestamp');
  74. } else {
  75. $this->error('Failed to generate items.json');
  76. }
  77. }
  78. }