lyhoshva / yii2-cover-behavior
Yii 2 图片上传行为
v1.2.3
2017-03-17 15:45 UTC
Requires
- php: >=5.4
- yiisoft/yii2: ^2.0
- yiisoft/yii2-imagine: ^2.0
README
Yii 2 图片上传行为
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一:
composer require --prefer-dist lyhoshva/yii2-cover-behavior
或添加
"lyhoshva/yii2-cover-behavior": "*"
到您的 composer.json 文件的 require 部分中。
基本用法
此扩展提供了对 ActiveRecord 图片上传的支持。此支持通过 [[\lyhoshva\Cover\CoverBehavior]] ActiveRecord 行为提供。您需要将其附加到您的 ActiveRecord 类,并指定以下选项:
class Article extends ActiveRecord { public function behaviors() { return [ 'image' => [ 'class' => CoverBehavior::className(), 'modelAttribute' => 'image_name', // attribute, which will contains image_name // virtual attribute, which is used for image uploading ("image" by default) 'relationReferenceAttribute' => 'image', 'path' => 'uploads/articles/', // path to upload directory ], ]; } public function rules() { return [ [['image'], 'required', 'on' => 'create'], [['image', 'cover_image'], 'file', 'extensions' => ['png', 'jpg', 'jpeg', 'gif']], ]; } }
注意:不要在拥有者 ActiveRecord 类中声明
relationReferenceAttribute
属性。确保它不会与任何现有拥有者字段或虚拟属性冲突。
通过 relationReferenceAttribute
声明的虚拟属性不仅用于保存,还包含已上传图片的现有引用
高级用法
行为可以通过编写生成规则并使用 回调函数 自动生成 路径 ('path'
)或 图片名称 ('fileNameGenerator'
)。或者,您可以设置静态的 路径 或 图片名称,指定字符串值。回调函数将 Active Record 模型对象作为参数。
您可以将 图片路径 ('modelAttributeFilePath'
)指定为模型属性以将生成的路径保存到数据库中。它只使用配置为回调函数的 路径。如果没有设置此选项并且 路径 是回调,则将图片路径保存到 'modelAttribute'
作为 图片路径 + 图片名称 字符串。
public function behaviors() { 'cover' => [ 'class' => CoverBehavior::className(), 'modelAttribute' => 'cover_name', 'relationAttribute' => 'cover', // not required options 'path' => function ($model) { return 'web/uploads/' . Inflector::slug($model->name) . '/'; // generated path should have forward slash at the end; }, 'modelAttributeFilePath' => 'cover_path', 'fileNameGenerator' => function ($model) { return Inflector::slug($model->name); }, ], }
缩略图
如果您想使用缩略图
public function behaviors() { return [ 'image' => [ 'class' => CoverBehavior::className(), 'modelAttribute' => 'image_name', // attribute, which will be handled // virtual attribute, which is used for image uploading ("image" by default) 'relationReferenceAttribute' => 'image', 'path' => 'uploads/articles/', // path to upload directory 'thumbnails' => [ [ 'prefix' => 'thumb_', //image prefix for thumbnail 'width' => 220, // max width 'height' => 160, // max height 'mode' => CoverBehavior::THUMBNAIL_INSET, ] ], ], ]; }
有关模块的信息,请参阅 [Imagine] (https://imagine.readthedocs.io/)