Tag Archive public

Byphunsanit

Laravel: manual Asset Cache data with JSON

เพราะว่ามี json ที่ export ทำไว้สำหรับให้ Vue.js หรือ JQuery ดึงข้อมูลไปใช้ เช่น ตัวเลือก options ใน select box ที่ใช้หลายที่ แต่บางครั้งนาน ๆ ทีจะมีการ update ข้อมูลบ้าง เลยเขียน code เอาไว้ update ข้อมูล และใช้ dynamic model ในการช่วยดึงข้อมูล อันนี้จะต่างจากแคชปกติของ laravel เพราะว่าจะเขียนไฟล์ไว้ใน SourceCode/public/assets/options เพราะต้องให้ javascript ทั้ง jQuery, React, Vue.js พวกนี้เข้ามาอ่านข้อมูลได้โดยที่ไม่ query ใหม่ ไม่ต้องใช้ PHP สร้างใหม่ทุกครั้ง หรือต้องมาตรวจดูข้อมูลทุกครั้งที่มีการใช้งาน จึงใช้เฉพาะส่วนที่เป็น public ได้เท่านั้น

  1. สร้าง Controller
    SourceCode/app/Http/Controllers/AssetCacheController.php
    อธิบาย
    บรรทัดที่ 21 เป็นการ load model แบบ dynamic ตามชื่อ model ที่ส่งมา
    บรรทัดที่ 24 เป็น function ที่ดึงข้อมูล option ที่เขียนเพิ่มไว้ใน model
    บรรทัดที่ 61 เป็นส่วนที่เขียนไว้ว่า key ไหน ให้ไปดึงข้อมูลจาก model อะไร
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    <?php
     
    namespace App\Http\Controllers;
     
    use Illuminate\Http\Request;
     
    class AssetCacheController extends Controller
    {
        /**
         * cacheSelectOptions
         *
         * @param string $key The key to use for the cache file
         * @param string $model The model to get the options from
         * @return write the options to a json file
         *
         * create a json file with the data from the model for the select option
         */
        public function cacheSelectOptions($key, $model)
        {
            // Perform operations with the model
            $modelClass = "App\\Models\\{$model}";
            if (class_exists($modelClass)) {
                if (method_exists($modelClass, 'getOptions')) {
                    $options = (new $modelClass)->getOptions();
     
                    $filePath = public_path('assets/options/' . $key . '.json');
     
                    file_put_contents($filePath, json_encode($options));
                } else {
                    \Log::error('AssetCacheController: Method getOptions() not found in model: ' . $model);
                }
            } else {
                \Log::error('AssetCacheController: Model ' . $model . ' not found');
            }
        }
     
        /**
         * getSelectOptions
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         *
         * create a json file with the data from the model for the select option and return the data
         */
        public function getSelectOptions(Request $request)
        {
            // Validate the request
            $validator = \Validator::make($request->all(), [
                'key' => 'required|string',
            ]);
     
            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()], 400);
            }
     
            // Get configuration
            $key = $request->input('key');
     
            switch ($key) {
     
                case 'category_id':
                    $model = 'Category';
                    break;
     
                case 'organization_id':
                    $model = 'Organization';
                    break;
     
                case 'service_line_id':
                    $model = 'ServiceLine';
                    break;
     
                case 'status_id':
                    $model = 'Status';
                    break;
     
                case 'team_id':
                    $model = 'Team';
                    break;
     
                case 'team_support_id':
                    $model = 'TeamUser';
                    break;
     
                case 'vessel_id':
                    $model = 'Vessel';
                    break;
     
                default:
                    \Log::error('AssetCacheController: no assets configuration for ' . $key);
                    return response()->json(['error' => 'Internal server error'], 500);
                    break;
     
            }
     
            $this->cacheSelectOptions($key, $model);
     
            $filePath = public_path('assets/options/' . $key . '.json');
     
            if (file_exists($filePath)) {
                $options = json_decode(file_get_contents($filePath), true);
                return response()->json($options);
            } else {
                return response()->json(['error' => 'Cache file not found'], 404);
            }
        }
    }
  2. สร้าง routes API โดยคำสั่ง
    php artisan install:api
  3. เพิ่ม rute
    Route::get('asset/getSelectOptions', [AssetCacheController::class, 'getSelectOptions']);
  4. test โดยลองเรียก url เช่น
    http://127.0.0.1:8000/api/asset/getSelectOptions?key=category_id
    ควรจะมี ไฟล์ SourceCode/public/assets/options/category_id ถูกสร้าง / อัพเดตตามข้อมูลในตาราง ณ ขณะนี้