mindtwo/laravel-decorator

Laravel Eloquent 模型装饰器

3.0.1 2024-03-13 08:35 UTC

This package is auto-updated.

Last update: 2024-09-13 09:41:48 UTC


README

Build Status StyleCI Quality Score Latest Stable Version Total Downloads MIT Software License

安装

您可以通过 composer 安装此软件包

composer require mindtwo/laravel-decorator

如何使用?

准备 Eloquent 模型

要使用装饰器,底层 eloquent 模型必须实现 Decoratable 接口。接下来,您应该使用 HasDecorator 特性,它实现了所需的方法。

use Illuminate\Database\Eloquent\Model;
use mindtwo\LaravelDecorator\Interfaces\Decoratable;
use mindtwo\LaravelDecorator\Traits\HasDecorator;

class MyModel extends Model implements Decoratable
{
    use HasDecorator;
}

您可以在 eloquent 模型上可选地设置一个默认装饰器,当您调用不带任何参数的 decorate() 方法时,将使用此装饰器。

use Illuminate\Database\Eloquent\Model;
use mindtwo\LaravelDecorator\Interfaces\Decoratable;
use mindtwo\LaravelDecorator\Traits\HasDecorator;

class MyModel extends Model implements Decoratable
{
    use HasDecorator;

    /**
     * Return the default decorator full qualified class name.
     *
     * @return string
     */
    public function defaultDecorator(): string
    {
        return MyDecorator::class;
    }
}

编写装饰器

要编写装饰器,只需扩展基本装饰器类。您可以通过 $this->model 属性访问底层 eloquent 模型。每当您尝试访问装饰器上的属性时,它将首先查找以大驼峰命名格式的函数。如果已定义,则将其调用,否则将其转发到底层 eloquent 模型。

use mindtwo\LaravelDecorator\Decorator;

class MyDecorator extends Decorator
{
    /**
     * Get formatted creation date.
     *
     * @return string
     */
    public function defaultDecorator(): string
    {
        return $this->model->created_at->format('Y-m-d');
    }
}

使用装饰器

要使用装饰器,只需在模型上调用 decorate() 方法。您可以使用装饰器类的完全限定名称作为参数来指定装饰器,否则将使用默认装饰器。

$myObject = MyModel::make();

// Use a certain decorator
$myDecoratedObject = $myObject->decorate(MyDecorator::class);

// Use the default decorator (needs to be defined on the model)
$myDecoratedObject = $myObject->decorate();

还可以在集合上调用 'decorate()' 方法,因为该软件包自动将其注册为宏。

$myCollection = MyModel::get();

// Use a certain decorator
$myDecoratedCollection = $myCollection->decorate(MyDecorator::class);

// Use the default decorator (needs to be defined on the model)
$myDecoratedCollection = $myCollection->decorate();

请注意,集合中的所有项目都必须实现 Decoratable 接口,否则将抛出异常。

更新日志

有关最近更改的更多信息,请参阅更新日志

贡献

有关详细信息,请参阅贡献指南

安全性

如果您发现任何与安全性相关的问题,请通过info@mindtwo.de发送电子邮件,而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅许可证文件