Pendekatan ini amat berguna untuk operasi pengiraan yang mahal atau ketika mewakili struktur data kompleks sebagai objek yang tepat dan bukannya array mudah.
Berikut adalah contoh yang menunjukkan pengendalian lokasi menggunakan objek nilai:
<?php namespace App\Models; use App\ValueObjects\Location; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Casts\Attribute; class Store extends Model { protected function location(): Attribute { return Attribute::make( get: fn ($value) => new Location( latitude: $this->latitude, longitude: $this->longitude, address: $this->address, timezone: $this->timezone ), set: function (Location $location) { return [ 'latitude' => $location->latitude, 'longitude' => $location->longitude, 'address' => $location->address, 'timezone' => $location->timezone ]; } )->shouldCache(); } protected function operatingHours(): Attribute { return Attribute::make( get: fn () => $this->calculateHours() )->withoutObjectCaching(); } private function calculateHours() { // Dynamic calculation based on timezone and current time return $this->location->getLocalHours(); } }
$store = Store::find(1); $store->location->address = '123 New Street'; $store->save(); // Access operating hours (dynamically recalculated) $hours = $store->operatingHours;
Atas ialah kandungan terperinci Prestasi dan objek nilai di aksesor laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!