首页 > 后端开发 > php教程 > 使用收集的Laravel自定义

使用收集的Laravel自定义

Emily Anne Brown
发布: 2025-03-06 02:17:09
原创
475 人浏览过

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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板