xelt2011/laravel-attachment

标签 Eloquent 模型附件包

v1.0.0 2019-11-30 02:16 UTC

This package is not auto-updated.

Last update: 2024-09-23 07:50:38 UTC


README

这是一个允许您在 Eloquent 模型中附加和管理文件的库。

安装

通过 composer 安装此包。

$ composer require xelt2011/laravel-attachment

注册服务提供者。

'providers' => [
    // ...

    Xelt2011\Attachment\AttachmentServiceProvider::class,

    // ...

使用方法

class Document extends Model
{
    use \Xelt2011\Attachment\AttachableTrait;

    // ...
}

$document = Document::first();

$document->attach($request->file('document'), [
  'path' => date('Y/m'),
  'filename' => '첨부 파일 #0001.pdf',
  'description' => '첨부 파일 설명',
]);

可下载的附件文件

class ImageGoods extends \Xelt2011\Attachment\AbstractAttachment
    implements \Xelt2011\Attachment\Contracts\Downloadable
{
    public function download()
    {
        return Storage::disk($this->disk_id)
            ->download($this->filepath, $this->filename);
    }
}

扩展

class Product extends Model
{
    use \Xelt2011\Attachment\AttachableTrait;

    public function images()
    {
        return $this->morphMany(ProductImage::class, 'attachable');
    }

    // ...
}

class ProductImage extends \Xelt2011\Attachment\AbstractAttachment
{
    const TYPE_ID = 'product-image';

    const STORAGE_DISK = 'public';

    const STORAGE_PATH = 'path/to';

    protected $thumbnailImageDisk = 'public';

    protected $thumbnailImagePath = 'path/to'

    public function getThumbnailImageUrlAttribute()
    {
        return Storage::disk($this->thumbnailImageDisk)
          ->url(sprintf('%s/%s', $this->thumbnailImagePath, $this->filepath));
    }

    protected static function boot()
    {
        parent::boot();

        static::retrieved(function ($model) {
            $model->append([
                'thumbnail_image_url',
            ]);
        });

        static::created(function ($model) {
            $content = $model->getFileContent();
            // 썸네일 이미지 생성
        });
    }
}

app(\Xelt2011\Attachment\AttachmentManager::class)
    ->extend('product-image', function () {
        return new ProductImage;
    });

$product = Product::first();
$product->attach($request->file('image'), [
    'type' => 'product-image',
    'group' => 'detail',
    'path' => date('Y/m'),
]);

$detailImages = $product->images()->byGroup('detail');