ORM Eloquent в Laravel вдосконалює функціональність accessor, пропонуючи вбудоване кешування та підтримку значеннєвих об'єктів. Ці можливості забезпечують ефективну обробку складних обчислень та структурованих даних, зберігаючи при цьому чистий і легко підтримуваний код.
Такий підхід є особливо корисним для операцій, що потребують значних обчислювальних ресурсів, або коли потрібно представляти складні структури даних у вигляді об'єктів, а не простих масивів.
protected function complexStats(): Attribute
{
return Attribute::make(
get: fn () => $this->calculateStats()
)->shouldCache();
}
Ось приклад реалізації роботи з місцями, використовуючи значеннєві об'єкти:
<?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()
{
// Динамічний розрахунок на основі часової зони та поточного часу
return $this->location->getLocalHours();
}
}
$store = Store::find(1);
$store->location->address = '123 New Street';
$store->save();
// Отримання робочих годин (перерахунок щоразу)
$hours = $store->operatingHours;
Функції accessor в Laravel забезпечують потужні інструменти для обробки складних структур даних і оптимізації продуктивності завдяки інтелектуальному кешуванню.
```