{"id":15169738,"url":"https://github.com/yii2tech/ar-file","last_synced_at":"2025-10-01T02:31:39.223Z","repository":{"id":57087030,"uuid":"48750834","full_name":"yii2tech/ar-file","owner":"yii2tech","description":"This package has been abandoned. See: https://www.patreon.com/posts/59332556","archived":true,"fork":false,"pushed_at":"2019-07-03T11:51:27.000Z","size":63,"stargazers_count":36,"open_issues_count":0,"forks_count":7,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-09-18T22:32:59.333Z","etag":null,"topics":["activerecord","attached-files","file","file-upload","files","image","images","transform","transformations","yii","yii2","yii2-extension"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yii2tech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["klimov-paul"],"patreon":"klimov_paul"}},"created_at":"2015-12-29T14:21:35.000Z","updated_at":"2024-03-27T13:55:49.000Z","dependencies_parsed_at":"2022-08-24T22:50:51.247Z","dependency_job_id":null,"html_url":"https://github.com/yii2tech/ar-file","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-file","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-file/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-file/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Far-file/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yii2tech","download_url":"https://codeload.github.com/yii2tech/ar-file/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219866483,"owners_count":16554235,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","attached-files","file","file-upload","files","image","images","transform","transformations","yii","yii2","yii2-extension"],"created_at":"2024-09-27T07:21:50.853Z","updated_at":"2025-10-01T02:31:38.913Z","avatar_url":"https://github.com/yii2tech.png","language":"PHP","funding_links":["https://github.com/sponsors/klimov-paul","https://patreon.com/klimov_paul"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yii2tech\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://avatars2.githubusercontent.com/u/12951949\" height=\"100px\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eActiveRecord File Attachment Extension for Yii2\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nThis extension provides support for ActiveRecord file attachment.\n\nFor license information check the [LICENSE](LICENSE.md)-file.\n\n[![Latest Stable Version](https://poser.pugx.org/yii2tech/ar-file/v/stable.png)](https://packagist.org/packages/yii2tech/ar-file)\n[![Total Downloads](https://poser.pugx.org/yii2tech/ar-file/downloads.png)](https://packagist.org/packages/yii2tech/ar-file)\n[![Build Status](https://travis-ci.org/yii2tech/ar-file.svg?branch=master)](https://travis-ci.org/yii2tech/ar-file)\n\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist yii2tech/ar-file\n```\n\nor add\n\n```json\n\"yii2tech/ar-file\": \"*\"\n```\n\nto the require section of your composer.json.\n\nIf you wish to use [[yii2tech\\ar\\file\\ImageFileBehavior]], you will also need to install [yiisoft/yii2-imagine](https://github.com/yiisoft/yii2-imagine),\nwhich is not required by default. In order to do so either run\n\n```\nphp composer.phar require --prefer-dist yiisoft/yii2-imagine\n```\n\nor add\n\n```json\n\"yiisoft/yii2-imagine\": \"*\"\n```\n\nto the require section of your composer.json.\n\n\nUsage\n-----\n\nThis extension provides support for ActiveRecord file attachment. Attached files are stored inside separated file storage,\nwhich does not connected with ActiveRecord database.\n\nThis extension based on [yii2tech/file-storage](https://github.com/yii2tech/file-storage), and uses it as a\nfile saving layer. Thus attached files can be stored at any file storage such as local file system, Amazon S3 and so on.\n\nFirst of all, you need to configure file storage, which will be used for attached files:\n\n```php\nreturn [\n    'components' =\u003e [\n        'fileStorage' =\u003e [\n            'class' =\u003e 'yii2tech\\filestorage\\local\\Storage',\n            'basePath' =\u003e '@webroot/files',\n            'baseUrl' =\u003e '@web/files',\n            'filePermission' =\u003e 0777,\n            'buckets' =\u003e [\n                'item' =\u003e [\n                    'baseSubPath' =\u003e 'item',\n                ],\n            ]\n        ],\n        // ...\n    ],\n    // ...\n];\n```\n\nYou should use [[\\yii2tech\\ar\\file\\FileBehavior]] behavior in order to allow your ActiveRecord file saving.\nThis can be done in following way:\n\n```php\nuse yii2tech\\ar\\file\\FileBehavior;\n\nclass Item extends \\yii\\db\\ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'file' =\u003e [\n                'class' =\u003e FileBehavior::className(),\n                'fileStorageBucket' =\u003e 'item',\n                'fileExtensionAttribute' =\u003e 'fileExtension',\n                'fileVersionAttribute' =\u003e 'fileVersion',\n            ],\n        ];\n    }\n    // ...\n}\n```\n\nUsage of this behavior requires extra columns being present at the owner entity (database table):\n\n - [[\\yii2tech\\ar\\file\\FileBehavior::fileExtensionAttribute]] - used to store file extension, allowing to determine file type\n - [[\\yii2tech\\ar\\file\\FileBehavior::fileVersionAttribute]] - used to track file version, allowing browser cache busting\n\nFor example, DDL for the 'item' table may look like following:\n\n```sql\nCREATE TABLE `Item`\n(\n   `id` integer NOT NULL AUTO_INCREMENT,\n   `name` varchar(64) NOT NULL,\n   `description` text,\n   `fileExtension` varchar(10),\n   `fileVersion` integer,\n    PRIMARY KEY (`id`)\n) ENGINE InnoDB;\n```\n\nOnce behavior is attached to may use `saveFile()` method on your ActiveRecord instance:\n\n```php\n$model = Item::findOne(1);\n$model-\u003esaveFile('/path/to/source/file.dat');\n```\n\nThis method will save source file inside file storage bucket, which has been specified inside behavior configuration,\nand update file extension and version attributes.\n\nYou may delete existing file using `deleteFile()` method:\n\n```php\n$model = Item::findOne(1);\n$model-\u003edeleteFile();\n```\n\n\u003e Note: attached file will be automatically removed on owner deletion (`delete()` method invocation).\n\nYou may check existence of the file, get its content or URL:\n\n```php\n$model = Item::findOne(1);\nif ($model-\u003efileExists()) {\n    echo $model-\u003egetFileUrl(); // outputs file URL\n    echo $model-\u003egetFileContent(); // outputs file content\n} else {\n    echo 'No file attached';\n}\n```\n\n\u003e Tip: you may setup [[\\yii2tech\\ar\\file\\FileBehavior::defaultFileUrl]] in order to make `getFileUrl()`\n  returning some default image URL in case actual attached file is missing.\n\n\n## Working with web forms \u003cspan id=\"working-with-web-forms\"\u003e\u003c/span\u003e\n\nUsually files for ActiveRecord are setup via web interface using file upload mechanism.\n[[\\yii2tech\\ar\\file\\FileBehavior]] provides a special virtual property for the owner, which name is determined\nby [[\\yii2tech\\ar\\file\\FileBehavior::fileAttribute]]. This property can be used to pass [[\\yii\\web\\UploadedFile]]\ninstance or local file name, which should be attached to the ActiveRecord. This property is processed on\nowner saving, and if set will trigger file saving. For example:\n\n```php\nuse yii\\web\\UploadedFile;\n\n$model = Item::findOne(1);\n$model-\u003efile = UploadedFile::getInstance($model, 'file');\n$model-\u003esave();\n\nvar_dump($model-\u003efileExists()); // outputs `true`\n```\n\n\u003e Attention: do NOT declare [[\\yii2tech\\ar\\file\\FileBehavior::fileAttribute]] attribute in the owner ActiveRecord class.\n  Make sure it does not conflict with any existing owner field or virtual property.\n\nIf [[\\yii2tech\\ar\\file\\FileBehavior::autoFetchUploadedFile]] is enabled, behavior will attempt to fetch\nuploaded file automatically before owner saving.\n\nYou may setup a validation rules for the file virtual attribute inside your model, specifying restrictions\nfor the attached file type, extension and so on:\n\n```php\nclass Item extends \\yii\\db\\ActiveRecord\n{\n    public function rules()\n    {\n        return [\n            // ...\n            ['file', 'file', 'mimeTypes' =\u003e ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'], 'skipOnEmpty' =\u003e !$this-\u003eisNewRecord],\n        ];\n    }\n    // ...\n}\n```\n\nInside view file you can use file virtual property for the form file input as it belongs to the owner model itself:\n\n```php\n\u003c?php\nuse yii\\helpers\\Html;\nuse yii\\widgets\\ActiveForm;\n\n/* @var $model Item */\n?\u003e\n\u003c?php $form = ActiveForm::begin(['options' =\u003e ['enctype' =\u003e 'multipart/form-data']]); ?\u003e\n\n\u003c?= $form-\u003efield($model, 'name'); ?\u003e\n\u003c?= $form-\u003efield($model, 'description'); ?\u003e\n\n\u003c?= $form-\u003efield($model, 'file')-\u003efileInput(); ?\u003e\n\n\u003cdiv class=\"form-group\"\u003e\n    \u003c?= Html::submitButton('Save', ['class' =\u003e 'btn btn-primary']) ?\u003e\n\u003c/div\u003e\n\n\u003c?php ActiveForm::end(); ?\u003e\n```\n\nInside the controller you don't need any special code:\n\n```php\nuse yii\\web\\Controller;\n\nclass ItemController extends Controller\n{\n    public function actionCreate()\n    {\n        $model = new Item();\n\n        if ($model-\u003eload(Yii::$app-\u003erequest-\u003epost()) \u0026\u0026 $model-\u003esave()) {\n            return $this-\u003eredirect(['view']);\n        } else {\n            return $this-\u003erender('create', [\n                'model' =\u003e $model,\n            ]);\n        }\n    }\n\n    // ...\n}\n```\n\n\n## File transformation \u003cspan id=\"file-transformation\"\u003e\u003c/span\u003e\n\nSaving file \"as it is\" is not always enough for ActiveRecord attachment. Often files require some\nprocessing, like image resizing, for example.\n\n[[\\yii2tech\\ar\\file\\TransformFileBehavior]] is an enhanced version of the [[FileBehavior]] developed for\nthe managing files, which require some processing (transformations).\nYou should setup [[\\yii2tech\\ar\\file\\TransformFileBehavior::transformCallback]] to specify actual file processing\nalgorithm, and [[\\yii2tech\\ar\\file\\TransformFileBehavior::fileTransformations]] providing the list of named\nprocessing and their specific settings. For example:\n\n```php\nuse yii2tech\\ar\\file\\TransformFileBehavior;\nuse yii\\imagine\\Image;\n\nclass Item extends \\yii\\db\\ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'file' =\u003e [\n                'class' =\u003e TransformFileBehavior::className(),\n                'fileStorageBucket' =\u003e 'item',\n                'fileExtensionAttribute' =\u003e 'fileExtension',\n                'fileVersionAttribute' =\u003e 'fileVersion',\n                'transformCallback' =\u003e function ($sourceFileName, $destinationFileName, $options) {\n                    try {\n                        Image::thumbnail($sourceFileName, $options['width'], $options['height'])-\u003esave($destinationFileName);\n                        return true;\n                    } catch (\\Exception $e) {\n                        return false;\n                    }\n                },\n                'fileTransformations' =\u003e [\n                    'origin', // no transformation\n                    'main' =\u003e [\n                        'width' =\u003e 400,\n                        'height' =\u003e 400,\n                    ],\n                    'thumbnail' =\u003e [\n                        'width' =\u003e 100,\n                        'height' =\u003e 100,\n                    ],\n                ],\n            ],\n        ];\n    }\n    // ...\n}\n```\n\nIn case of usage [[\\yii2tech\\ar\\file\\TransformFileBehavior]] methods `fileExists()`, `getFileContent()` and `getFileUrl()`\naccepts first parameter as a transformation name, for which result should be returned:\n\n```php\n$model = Item::findOne(1);\necho $model-\u003egetFileUrl('origin'); // outputs URL for the full-sized image\necho $model-\u003egetFileUrl('main'); // outputs URL for the medium-sized image\necho $model-\u003egetFileUrl('thumbnail'); // outputs URL for the thumbnail image\n```\n\nSome file transformations may require changing the file extension. For example: you may want to create a preview for the\n*.psd file in *.jpg format. You may specify file extension per each transformation using [[\\yii2tech\\ar\\file\\TransformFileBehavior::transformationFileExtensions]].\nFor example:\n\n```php\nuse yii2tech\\ar\\file\\TransformFileBehavior;\nuse yii\\imagine\\Image;\n\nclass Item extends \\yii\\db\\ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'file' =\u003e [\n                'class' =\u003e TransformFileBehavior::className(),\n                'fileTransformations' =\u003e [\n                    'origin', // no transformation\n                    'preview' =\u003e [\n                        // ...\n                    ],\n                    'web' =\u003e [\n                        // ...\n                    ],\n                ],\n                'transformationFileExtensions' =\u003e [\n                    'preview' =\u003e 'jpg',\n                    'web' =\u003e function ($fileExtension) {\n                        return in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif']) ? $fileExtension : 'jpg';\n                    },\n                ],\n                // ...\n            ],\n        ];\n    }\n    // ...\n}\n```\n\nYou may face the issue, when settings for some file transformations change or new transformation added, as your project\nevolves, making existing saved files outdated. In this case you can use [[\\yii2tech\\ar\\file\\TransformFileBehavior::regenerateFileTransformations()]]\nmethod to regenerate transformation files with new settings using some existing transformation as source.\nFor example:\n\n```php\n$model = Item::findOne(1);\n$model-\u003eregenerateFileTransformations('origin'); // regenerate transformations using 'origin' as a source\n```\n\n\n## Image file transformation \u003cspan id=\"image-file-transformation\"\u003e\u003c/span\u003e\n\nThe most common file transformation use case is an image resizing. Thus a special behavior\n[[\\yii2tech\\ar\\file\\ImageFileBehavior]] is provided. This behavior provides image resize transformation\nvia [yiisoft/yii2-imagine](https://github.com/yiisoft/yii2-imagine) extension.\nConfiguration example:\n\n```php\nuse yii2tech\\ar\\file\\ImageFileBehavior;\n\nclass Item extends \\yii\\db\\ActiveRecord\n{\n    public function behaviors()\n    {\n        return [\n            'file' =\u003e [\n                'class' =\u003e ImageFileBehavior::className(),\n                'fileStorageBucket' =\u003e 'item',\n                'fileExtensionAttribute' =\u003e 'fileExtension',\n                'fileVersionAttribute' =\u003e 'fileVersion',\n                'fileTransformations' =\u003e [\n                    'origin', // no resize\n                    'main' =\u003e [800, 600], // width = 800px, height = 600px\n                    'thumbnail' =\u003e [100, 80], // width = 100px, height = 80px\n                ],\n            ],\n        ];\n    }\n    // ...\n}\n```\n\n\u003e Note: this package does not include \"yiisoft/yii2-imagine\", you should install it yourself.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-file","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyii2tech%2Far-file","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Far-file/lists"}