kaliel / cakephp-image
CakePHP 4.0 图片上传行为
2.0.0
2020-03-05 13:41 UTC
Requires
- php: >=7.2
- cakephp/cakephp: ^4.0
- intervention/image: ^2.5
Requires (Dev)
- cakephp/cakephp-codesniffer: ~4.0.0
- phpunit/phpunit: ^8.5
README
图片行为,通过为返回的每个实体添加包含图片数据的字段,类似于 Cake 内置的 Translate 行为。
- 上传可以是基于 $_FILE 或仅包含路径的字符串。相应地使用 'copy' 或 'move_uploaded_file'。
- 验证应通过 cake 的良好验证选项完成,因此不包括在行为本身中。
- 使用 Intervention/Image 生成图片预设。请参阅 文档 页面。
注意
该行为仍在开发中,不应在任何方面被认为是稳定的。
配置参数
- fields: 用于图片的字段,应为字段名称作为键,类型作为值(many, one)
- presets: 包含 Intervention/Image 方法及其参数的预设数组,也可以是传递图片对象的可调用函数
- path: 上传图片应存储的基本路径
- table: 存储图片数据的数据表名称(参见 Config/Schema/images.sql)
- manager: Intervention\Image\ImageManager 的设置(默认为 driver : imagick)
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中
php composer.phar require kaliel/image
通过在您的项目 src/Application.php
中添加以下语句来加载插件
public function bootstrap(): void { parent::bootstrap(); $this->addPlugin('Image'); }
使用 cakephp 的迁移来初始化数据库表
bin/cake migrations migrate -p Image
通过将其添加到表的初始化钩子中启用图片行为
public function initialize(array $config) { $this->addBehavior('Image.Image', [ 'path' => WWW_ROOT . 'assets', 'fields' => [ 'images' => 'many', 'main' => 'one' ], ]); }
图片预设
图片处理由 Intervention/Image 处理,配置预设非常简单。以下示例中预设 'overview' 是通过遍历各种 Intervention/Image 辅助函数生成的。
$this->addBehavior('Image.Image', [ 'path' => WWW_ROOT . 'assets', 'presets' => [ 'overview' => [ 'resize' => [ 200, 200 ], // $image->resize(200, 200); 'crop' => [ 150, 150] // $image->crop(150,150); 'canvas' => function($image) { // you can use callback functions for more advanced stuff // do some fancy stuff here return $image; }, ] ], 'fields' => [ 'image' => 'one' ], ]);
辅助工具
我已包括了一个基本辅助工具来渲染您的模板中的图片。
$this->Image->render($entity->field); // Original image $this->Image->render($entity->field, [ 'preset' => 'presetName' ]); // Preset $this->Image->render($entity->field, [ 'preset' => 'presetName', 'alt' => 'Cool image' ]); // Preset + image attributes $this->Image->url($entity->field, 'presetName'); // Returns the image path with an optional preset argument
Shell
简单的 Shell,用于重新生成给定模型的所有预设。
bin/cake image