yii2tech/ar-file
最新稳定版本:1.0.3
Composer 安装命令:
composer require yii2tech/ar-file
包简介
Provides support for ActiveRecord file attachment
README 文档
README
ActiveRecord File Attachment Extension for Yii2
This extension provides support for ActiveRecord file attachment.
For license information check the LICENSE-file.
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist yii2tech/ar-file
or add
"yii2tech/ar-file": "*"
to the require section of your composer.json.
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
php composer.phar require --prefer-dist yiisoft/yii2-imagine
or add
"yiisoft/yii2-imagine": "*"
to the require section of your composer.json.
Usage
This extension provides support for ActiveRecord file attachment. Attached files are stored inside separated file storage, which does not connected with ActiveRecord database.
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.
First of all, you need to configure file storage, which will be used for attached files:
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:
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):
- [[\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:
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:
$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.
You may delete existing file using deleteFile() method:
$model = Item::findOne(1); $model->deleteFile();
Note: attached file will be automatically removed on owner deletion (
delete()method invocation).
You may check existence of the file, get its content or URL:
$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.
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:
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.
If [[\yii2tech\ar\file\FileBehavior::autoFetchUploadedFile]] is enabled, behavior will attempt to fetch uploaded file automatically before owner saving.
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:
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:
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $model Item */ ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?= $form->field($model, 'name'); ?> <?= $form->field($model, 'description'); ?> <?= $form->field($model, 'file')->fileInput(); ?> <div class="form-group"> <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?>
Inside the controller you don't need any special code:
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.
[[\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:
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:
$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:
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:
$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:
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.
yii2tech/ar-file 适用场景与选型建议
yii2tech/ar-file 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 60.36k 次下载、GitHub Stars 达 36, 最近一次更新时间为 2015 年 12 月 29 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「image」 「file」 「thumbnail」 「active」 「record」 「attachment」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 yii2tech/ar-file 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 yii2tech/ar-file 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 yii2tech/ar-file 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
The file manager intended for using Laravel with CKEditor / TinyMCE / Colorbox
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
The Yii2 extension uses jQuery jquery.carousel-1.1.min.js and makes image carousel from php array of structure defined.
A PHP library for fetching thumbnails from a URL
The Yii2 extension uses jQuery PrettyPhoto and OwlCarousel js and makes image galary from php array of structure defined.
A Gokaru storage & thumbnail server PHP client
统计信息
- 总下载量: 60.36k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 38
- 点击次数: 19
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2015-12-29