Code Monkey home page Code Monkey logo

yii2-file's Introduction

Файловая библиотека для Yii2

Содержит следующий функционал:

  • FileStore - абстракция файлового хранилища;

    • LocaFileStore - реализация хранилища в локальной файловой системе;
    • FtpFileStore - хранилище файлов на FTP;
    • SftpFileStore - хранилище файлов через SFTP;
    • FlysystemFileStore - хранилище через библиотеку Flysystem;
  • File - абстракция файла, поддержка операций с файлом;

    • UploadFile - загрузка файлов в хранилище из другого файла или данных $_FILES;
    • ThumbFile - создание превью картинок с кешем на диске;
    • CSVFile - абстракция для работы с CSV-файлами;
      • CSVResponseFormatter - формирование ответа в виде CSV-файла;
  • FileAttributeBehavior - поддержка файловых аттрибутов моделей;

  • FileInputWidget - поддержка полей форм для загрузки и редактирования файлов/картинок аттрибутов моделей;

Работа с файловым хранилищем

Конфигурация компонента на примере локального хранилища файлов:

$config = [
    'components' => [
        // хранилище файлов
        'fileStore' => [
            'class' => dicr\file\LocalFileStore::class,
            'path' => '@webroot/files', // базовый путь на диске
            'url' => '@web/files' // базовый URL для скачивания (опционально)
        ]
    ]
];

Использование:

/** @var dicr\file\FileStore $store получаем настроенный компонент хранилища */
$store = Yii::$app->get('fileStore');

// или например хранилище в локальной файловой системе
$store2 = dicr\file\LocalFileStore::root();

// список файлов хранилища в директории pdf
$files = $store->list('pdf');

// Получаем файл по имени
$file = $store->file('pdf/my-report.pdf');

// выводим содержимое файла
echo $file->content;

// выводим url файла в хранилище
echo $file->url;

Создание превью картинок

Для работы с превью нужно настроить кеш картинок в локальной файловой системе:

$config = [
    'components' => [
        // хранилище для превью картинок
        'thumbStore' => [
            'class' => dicr\file\LocalFileStore::class,
            'path' => '@webroot/thumb',
            'url' => '@web/thumb',
        ],
    
        // основное хранилище файлов
        'fileStore' => [
            'class' => dicr\file\LocalFileStore::class,
            'path' => '@webroot/files',
            // конфигурация компонента для создания превью
            'thumbFileConfig' => [
                'store' => 'thumbStore', // компонент хранилища для кэша картинок
                'noimage' => '@webroot/res/img/noimage.png' // заглушка для создания превью несуществующих файлов моделей
            ]
        ]
    ]
];

Использование превью:

use yii\helpers\Html;
use dicr\file\FileStore;

/** @var FileStore $store */
$store = Yii::$app->get('fileStore');

// получаем файл из хранилища
$file = $store->file('images/image.jpg');

// выводим картинку превью
echo Html::img($file->thumb(['width' => 320, 'height' => 240])->url);

Файловые аттрибуты модели

Пример модели товара:

use yii\db\ActiveRecord;
use dicr\file\File;
use dicr\file\FileAttributeBehavior;

/**
 * @property-read ?File $image одна картинка
 * @property-read File[] $docs набор файлов документов
 * 
 * FileAttributeBehavior
 * 
 * @method bool loadFileAttributes($formName = null)
 * @method saveFileAttributes()
 * @method File|File[]|null getFileAttribute(string $attribute, bool $refresh = false)
 */
class Product extends ActiveRecord
{
    /**
     * @inheritDoc
     */
    public function behaviors() : array
    {
        return [
            // добавляем файловые аттрибуты
            'file' => [
                'class' => FileAttributeBehavior::class,
                'attributes' => [
                    'image' => 1, // одна картинка
                    'docs' => 0 // неограниченное кол-во файлов
                ]
            ]   
        ];       
    }

    /**
     * @inheritDoc
     */
    public function load($data, $formName = null) : bool
    {
        $ret = parent::load($data, $formName);

        // загружаем файловые аттрибуты
        if ($this->loadFileAttributes($formName)) {
            $ret = true;
        }

        return $ret;
    }
}

Использование файловых аттрибутов:

use dicr\file\UploadFile;use yii\db\ActiveRecord;use yii\helpers\Html;

/**
 * @var ActiveRecord $model
 */

// добавляем картинку товару
$model->image = new UploadFile('/tmp/newimage.jpg');

// сохраняем
$model->save();

// выводим превью картинки товара
echo Html::img((string)$model->image->thumb(['width' => 320, 'height' => 200]));

// выводим ссылки загрузки файлов товара
foreach ($model->docs ?: [] as $doc) {
    echo Html::a($doc->name, $doc->url);
}

Форма редактирования файлов товара:

use dicr\file\FileInputWidget;use yii\db\ActiveRecord;
use yii\widgets\ActiveForm;

/**
 * @var ActiveForm $form
 * @var ActiveRecord $model
 */

// поле с виджетом редактирования картинки
echo $form->field($model, 'image')->widget(FileInputWidget::class, [
  'layout' => 'images',
  'limit' => 1,
  'accept' => 'image/*',
  'removeExt' => true
]);

// поле с виджетом редактирования документов
echo $form->field($model, 'docs')->widget(FileInputWidget::class, [
  'layout' => 'files',
  'limit' => 0,
  'removeExt' => true
]);

yii2-file's People

Contributors

dicrtarasov avatar

Watchers

 avatar  avatar  avatar

yii2-file's Issues

Bootstrap 4 не поддерживается?

так случилось что у меня в проекте Bootstrap 4, как мне установить ваше компонент?

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - yiisoft/yii2-bootstrap5[2.0.1, ..., 2.0.3] require bower-asset/bootstrap ^5.1.0 -> found bower-asset/bootstrap[v5.1.0, v5.1.1, v5.1.2, v5.1.3] but the package is fixed to v3.4.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - dicr/yii2-file[8.1.0, ..., 8.1.9] require dicr/yii2-asset ~3.0 -> satisfiable by dicr/yii2-asset[3.0.0, 3.0.1, 3.0.2].
    - dicr/yii2-asset[3.0.0, ..., 3.0.2] require yiisoft/yii2-bootstrap5 ~2.0 -> satisfiable by yiisoft/yii2-bootstrap5[2.0.1, 2.0.2, 2.0.3].
    - Root composer.json requires dicr/yii2-file ^8.1 -> satisfiable by dicr/yii2-file[8.1.0, ..., 8.1.9].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require dicr/yii2-file:*" to figure out if any version is installable, or "composer require dicr/yii2-file:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.