igaster/eloquent-decorator

一个简单的特质,实现了Laravel eloquent模型上的装饰器模式。

v1.0.2 2019-10-11 18:57 UTC

This package is auto-updated.

Last update: 2024-09-12 05:26:35 UTC


README

Laravel Downloads Build Status License

一个简单的特质,实现了Laravel eloquent模型上的装饰器模式。

使用方法

  • 在不继承的情况下扩展模型(组合与继承)
  • 创建模型的多种变体

案例研究

通常需要每种图像的多个版本。您的基类(Image)处理数据库、关系等。

您的装饰器模型(例如缩略图、profileImage)可能对原始图像进行图像处理以创建变体。例如,它们可以覆盖基类的src()方法,指向不同的文件。所有装饰版本共享数据库中的相同记录,但可以更改它们的表示和行为!

更多想法

  • 基类:User。装饰对象:Member、Moderator、SuperUser等
  • 基类:Article。装饰对象:FeaturedArticle、BlogPost等

安装

编辑您的项目composer.json文件以要求

"require": {
    "igaster/eloquent-decorator": "~1.0"
}

并使用`composer update`安装

实现装饰器模式

步骤1:类声明

您的类应实现一些接口以模仿Eloquent模型的行为

use igaster\EloquentDecorator\EloquentDecoratorTrait;

use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Queue\QueueableEntity;
use ArrayAccess;
use JsonSerializable;

class SuperUser implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
    use EloquentDecoratorTrait;

    public $newProperty;		// Add a new property
    public $overridenPropery;	// or Overide a property (it hides it)

    public function TruncateDatabase(){
    	// add your functions...
    }
}

步骤2:装饰Eloquent模型

	$user = User::find(1);

	$superUser = SuperUser::wrap($user);

	// you can think the SuperUser class as inhereted from the User model. so you can still do:

	$superUser->name = "Admin";
	$superUser->save();

	// But you also have access to SuperUser functions/attributes:

	$superUser->TruncateDatabase();

	// You can always access to the original (decorated object):
	$superUser->object->someProperty;
}

需要构造函数吗?

您必须覆盖EloquentDecoratorTrait并创建自己的工厂函数。不要忘记在最后调用self::wrap($object)