首頁 >後端開發 >php教程 >使用收集的Laravel自定義

使用收集的Laravel自定義

Emily Anne Brown
Emily Anne Brown原創
2025-03-06 02:17:09477瀏覽

Collection Customization in Laravel Using CollectedBy

通過Laravel's

屬性增強雄辯的收集功能。 該屬性提供了一種簡化的方法,可以定制特定型號類型的集合,從而促進清潔劑,更可維護的代碼。 忘記覆蓋CollectedBy方法; newCollection()在班級級別提供聲明的解決方案。 CollectedBy 以前,

剪裁模型收集涉及覆蓋

的方法。 這種新的基於屬性的方法提供了一個卓越的類級解決方案。 newCollection()>

use Illuminate\Database\Eloquent\Attributes\CollectedBy;

#[CollectedBy(CustomCollection::class)]
class YourModel extends Model
{
    // Model implementation
}
考慮電子商務產品目錄:

// Product Collection
<?php namespace App\Collections;

use Illuminate\Database\Eloquent\Collection;

class ProductCollection extends Collection
{
    public function inStock()
    {
        return $this->filter(fn($product) => $product->stock_count > 0);
    }

    public function onSale()
    {
        return $this->filter(fn($product) => $product->discount_percentage > 0);
    }

    public function byPriceRange($min, $max)
    {
        return $this->filter(function($product) use ($min, $max) {
            $price = $product->getEffectivePrice();
            return $price >= $min && $price <= $max;
        });
    }

    public function topRated()
    {
        return $this->filter(fn($product) => $product->average_rating >= 4)
            ->sortByDesc('average_rating');
    }
}

//Product model
namespace App\Models;

use App\Collections\ProductCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\CollectedBy;

#[CollectedBy(ProductCollection::class)]
class Product extends Model
{
    public function getEffectivePrice()
    {
        return $this->discount_percentage > 0 ? $this->price * (1 - $this->discount_percentage / 100) : $this->price;
    }
}

屬性簡化了集合的自定義,從而產生了更清潔,更可讀的Laravel應用程序。

以上是使用收集的Laravel自定義的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn