2017 © Pedro Peláez
 

yii2-extension ar-file

Provides support for ActiveRecord file attachment

image

yii2tech/ar-file

Provides support for ActiveRecord file attachment

  • Thursday, July 27, 2017
  • by klimov-paul
  • Repository
  • 4 Watchers
  • 33 Stars
  • 9,107 Installations
  • PHP
  • 2 Dependents
  • 0 Suggesters
  • 5 Forks
  • 0 Open issues
  • 5 Versions
  • 7 % Grown

The README.md

, (*1)

ActiveRecord File Attachment Extension for Yii2


This extension provides support for ActiveRecord file attachment., (*2)

For license information check the LICENSE-file., (*3)

Latest Stable Version Total Downloads Build Status, (*4)

Installation

The preferred way to install this extension is through composer., (*5)

Either run, (*6)

php composer.phar require --prefer-dist yii2tech/ar-file

or add, (*7)

"yii2tech/ar-file": "*"

to the require section of your composer.json., (*8)

If you wish to use [[yii2tech\ar\file\ImageFileBehavior]], you will also need to install yiisoft/yii2-imagine, which is not required by default. In order to do so either run, (*9)

php composer.phar require --prefer-dist yiisoft/yii2-imagine

or add, (*10)

"yiisoft/yii2-imagine": "*"

to the require section of your composer.json., (*11)

Usage

This extension provides support for ActiveRecord file attachment. Attached files are stored inside separated file storage, which does not connected with ActiveRecord database., (*12)

This extension based on yii2tech/file-storage, and uses it as a file saving layer. Thus attached files can be stored at any file storage such as local file system, Amazon S3 and so on., (*13)

First of all, you need to configure file storage, which will be used for attached files:, (*14)

return [
    'components' => [
        'fileStorage' => [
            'class' => 'yii2tech\filestorage\local\Storage',
            'basePath' => '@webroot/files',
            'baseUrl' => '@web/files',
            'filePermission' => 0777,
            'buckets' => [
                'item' => [
                    'baseSubPath' => 'item',
                ],
            ]
        ],
        // ...
    ],
    // ...
];

You should use [[\yii2tech\ar\file\FileBehavior]] behavior in order to allow your ActiveRecord file saving. This can be done in following way:, (*15)

use yii2tech\ar\file\FileBehavior;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'file' => [
                'class' => FileBehavior::className(),
                'fileStorageBucket' => 'item',
                'fileExtensionAttribute' => 'fileExtension',
                'fileVersionAttribute' => 'fileVersion',
            ],
        ];
    }
    // ...
}

Usage of this behavior requires extra columns being present at the owner entity (database table):, (*16)

  • [[\yii2tech\ar\file\FileBehavior::fileExtensionAttribute]] - used to store file extension, allowing to determine file type
  • [[\yii2tech\ar\file\FileBehavior::fileVersionAttribute]] - used to track file version, allowing browser cache busting

For example, DDL for the 'item' table may look like following:, (*17)

CREATE TABLE `Item`
(
   `id` integer NOT NULL AUTO_INCREMENT,
   `name` varchar(64) NOT NULL,
   `description` text,
   `fileExtension` varchar(10),
   `fileVersion` integer,
    PRIMARY KEY (`id`)
) ENGINE InnoDB;

Once behavior is attached to may use saveFile() method on your ActiveRecord instance:, (*18)

$model = Item::findOne(1);
$model->saveFile('/path/to/source/file.dat');

This method will save source file inside file storage bucket, which has been specified inside behavior configuration, and update file extension and version attributes., (*19)

You may delete existing file using deleteFile() method:, (*20)

$model = Item::findOne(1);
$model->deleteFile();

Note: attached file will be automatically removed on owner deletion (delete() method invocation)., (*21)

You may check existence of the file, get its content or URL:, (*22)

$model = Item::findOne(1);
if ($model->fileExists()) {
    echo $model->getFileUrl(); // outputs file URL
    echo $model->getFileContent(); // outputs file content
} else {
    echo 'No file attached';
}

Tip: you may setup [[\yii2tech\ar\file\FileBehavior::defaultFileUrl]] in order to make getFileUrl() returning some default image URL in case actual attached file is missing., (*23)

Working with web forms

Usually files for ActiveRecord are setup via web interface using file upload mechanism. [[\yii2tech\ar\file\FileBehavior]] provides a special virtual property for the owner, which name is determined by [[\yii2tech\ar\file\FileBehavior::fileAttribute]]. This property can be used to pass [[\yii\web\UploadedFile]] instance or local file name, which should be attached to the ActiveRecord. This property is processed on owner saving, and if set will trigger file saving. For example:, (*24)

use yii\web\UploadedFile;

$model = Item::findOne(1);
$model->file = UploadedFile::getInstance($model, 'file');
$model->save();

var_dump($model->fileExists()); // outputs `true`

Attention: do NOT declare [[\yii2tech\ar\file\FileBehavior::fileAttribute]] attribute in the owner ActiveRecord class. Make sure it does not conflict with any existing owner field or virtual property., (*25)

If [[\yii2tech\ar\file\FileBehavior::autoFetchUploadedFile]] is enabled, behavior will attempt to fetch uploaded file automatically before owner saving., (*26)

You may setup a validation rules for the file virtual attribute inside your model, specifying restrictions for the attached file type, extension and so on:, (*27)

class Item extends \yii\db\ActiveRecord
{
    public function rules()
    {
        return [
            // ...
            ['file', 'file', 'mimeTypes' => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'], 'skipOnEmpty' => !$this->isNewRecord],
        ];
    }
    // ...
}

Inside view file you can use file virtual property for the form file input as it belongs to the owner model itself:, (*28)


 ['enctype' => 'multipart/form-data']]); ?>

= $form->field($model, 'name'); ?>
= $form->field($model, 'description'); ?>

= $form->field($model, 'file')->fileInput(); ?>



= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>

Inside the controller you don't need any special code:, (*29)

use yii\web\Controller;

class ItemController extends Controller
{
    public function actionCreate()
    {
        $model = new Item();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    // ...
}

File transformation

Saving file "as it is" is not always enough for ActiveRecord attachment. Often files require some processing, like image resizing, for example., (*30)

[[\yii2tech\ar\file\TransformFileBehavior]] is an enhanced version of the [[FileBehavior]] developed for the managing files, which require some processing (transformations). You should setup [[\yii2tech\ar\file\TransformFileBehavior::transformCallback]] to specify actual file processing algorithm, and [[\yii2tech\ar\file\TransformFileBehavior::fileTransformations]] providing the list of named processing and their specific settings. For example:, (*31)

use yii2tech\ar\file\TransformFileBehavior;
use yii\imagine\Image;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'file' => [
                'class' => TransformFileBehavior::className(),
                'fileStorageBucket' => 'item',
                'fileExtensionAttribute' => 'fileExtension',
                'fileVersionAttribute' => 'fileVersion',
                'transformCallback' => function ($sourceFileName, $destinationFileName, $options) {
                    try {
                        Image::thumbnail($sourceFileName, $options['width'], $options['height'])->save($destinationFileName);
                        return true;
                    } catch (\Exception $e) {
                        return false;
                    }
                },
                'fileTransformations' => [
                    'origin', // no transformation
                    'main' => [
                        'width' => 400,
                        'height' => 400,
                    ],
                    'thumbnail' => [
                        'width' => 100,
                        'height' => 100,
                    ],
                ],
            ],
        ];
    }
    // ...
}

In case of usage [[\yii2tech\ar\file\TransformFileBehavior]] methods fileExists(), getFileContent() and getFileUrl() accepts first parameter as a transformation name, for which result should be returned:, (*32)

$model = Item::findOne(1);
echo $model->getFileUrl('origin'); // outputs URL for the full-sized image
echo $model->getFileUrl('main'); // outputs URL for the medium-sized image
echo $model->getFileUrl('thumbnail'); // outputs URL for the thumbnail image

Some file transformations may require changing the file extension. For example: you may want to create a preview for the *.psd file in *.jpg format. You may specify file extension per each transformation using [[\yii2tech\ar\file\TransformFileBehavior::transformationFileExtensions]]. For example:, (*33)

use yii2tech\ar\file\TransformFileBehavior;
use yii\imagine\Image;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'file' => [
                'class' => TransformFileBehavior::className(),
                'fileTransformations' => [
                    'origin', // no transformation
                    'preview' => [
                        // ...
                    ],
                    'web' => [
                        // ...
                    ],
                ],
                'transformationFileExtensions' => [
                    'preview' => 'jpg',
                    'web' => function ($fileExtension) {
                        return in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif']) ? $fileExtension : 'jpg';
                    },
                ],
                // ...
            ],
        ];
    }
    // ...
}

You may face the issue, when settings for some file transformations change or new transformation added, as your project evolves, making existing saved files outdated. In this case you can use [[\yii2tech\ar\file\TransformFileBehavior::regenerateFileTransformations()]] method to regenerate transformation files with new settings using some existing transformation as source. For example:, (*34)

$model = Item::findOne(1);
$model->regenerateFileTransformations('origin'); // regenerate transformations using 'origin' as a source

Image file transformation

The most common file transformation use case is an image resizing. Thus a special behavior [[\yii2tech\ar\file\ImageFileBehavior]] is provided. This behavior provides image resize transformation via yiisoft/yii2-imagine extension. Configuration example:, (*35)

use yii2tech\ar\file\ImageFileBehavior;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'file' => [
                'class' => ImageFileBehavior::className(),
                'fileStorageBucket' => 'item',
                'fileExtensionAttribute' => 'fileExtension',
                'fileVersionAttribute' => 'fileVersion',
                'fileTransformations' => [
                    'origin', // no resize
                    'main' => [800, 600], // width = 800px, height = 600px
                    'thumbnail' => [100, 80], // width = 100px, height = 80px
                ],
            ],
        ];
    }
    // ...
}

Note: this package does not include "yiisoft/yii2-imagine", you should install it yourself., (*36)

The Versions

27/07 2017

dev-master

9999999-dev

Provides support for ActiveRecord file attachment

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

file yii2 image transformation active thumbnail record attachment

22/06 2017

1.0.3

1.0.3.0

Provides support for ActiveRecord file attachment

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

file yii2 image transformation active thumbnail record attachment

07/10 2016

1.0.2

1.0.2.0

Provides support for ActiveRecord file attachment

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

file yii2 image active thumbnail record attachment

14/02 2016

1.0.1

1.0.1.0

Provides support for ActiveRecord file attachment

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

file yii2 image active thumbnail record attachment

10/02 2016

1.0.0

1.0.0.0

Provides support for ActiveRecord file attachment

  Sources   Download

BSD-3-Clause

The Requires

 

by Paul Klimov

file yii2 image active thumbnail record attachment