编程

Laravel 访问器中的值对象及性能提升

109 2025-04-09 18:26:00

Laravel 的 Eloquent ORM 通过内置缓存和值对象支持增强了访问器功能。这些特性能够有效地处理复杂的计算和结构化数据,同时保持干净、可维护的代码。

当处理计算成本高昂的操作或需要将复杂的数据结构表示为适当的对象而不是普通数组时,这种方法被证明特别有价值。

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()
    {
        // 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 (recalculated each time)
$hours = $store->operatingHours;

Laravel 的访问器特性为处理复杂的数据结构和通过智能缓存优化性能提供了强大的工具