unique / yii2-model-image
允许在Yii2框架中轻松将图像附加到模型
dev-master
2023-04-24 12:32 UTC
Requires
- php: >=8.0
- ext-dom: *
- yiisoft/yii2: ~2.0.0
- yiisoft/yii2-imagine: ~2.2.0
Requires (Dev)
- phpunit/phpunit: ^9.4
This package is auto-updated.
Last update: 2024-09-24 15:40:41 UTC
README
Yii2框架模型类的行为,允许在保存模型时轻松附加图像。
安装
安装此扩展的首选方式是通过 Composer。
运行以下命令
composer require unique/yii2-model-image
或
"unique/yii2-model-image": "@dev"
将以下内容添加到您的 composer.json
文件的 require 部分。
要创建数据库表,请运行迁移文件
./yii migrate --migrationPath="vendor/unique/yii2-model-image/src/migrations"
使用方法
为了使用此行为,您首先需要加载模块。模块只能加载一次。将以下内容添加到您的配置文件中
<?php [ 'bootstrap' => [ // ..., 'images' ], // ... 'modules' => [ 'images' => [ 'class' => \unique\yii2modelimage\ModelImageModule::class, // Defines an alias friendly path, where to store all the images 'images_path' => '@app/www/images', // specify an Image class to use for generating images // should either extend the default class or implement methods needed 'image_class' => \unique\yii2modelimage\models\Image::class, // Should list ImageDimensions for all image version groups, i.e.: 'group_versions' => [ // 'user_profile_photo' => [ // 'thumb_small' => ( new ImageDimensions( 'thumb_small', null, 80 ) )->asResized()->setQuality( 80 ), // 'thumb_large' => ( new ImageDimensions( 'thumb_large', null, 800 ) )->asResized()->setQuality( 80 ), // ], ], ], // ... ] ] ?>
然后,您的模型可以实现类似的行为
class Profile extends \yii\db\ActiveRecord { // ... public $profile_photo; public function behaviors() { return array_merge( parent::behaviors(), [ 'image' => [ 'class' => ImageBehavior::class, 'uploaded_file_attribute' => 'profile_photo', 'image_attribute' => 'profile_photo_id', 'group' => 'user_profile_photo', ] ] ); } public function rules() { return [ // ... [ [ 'profile_photo' ], 'file', 'extensions' => 'jpg' ], ]; } }
现在,当保存 Profile 模型时,上传的图像将被自动保存,并生成两个关联的图像版本,称为 thumb_small
和 thumb_large
。如果在保存图像时发生错误,则 Profile::save()
将返回 false,并且将在 Profile::$profile_photo
属性上设置错误。