3xw/附件

此包已被弃用且不再维护。作者建议使用 3xw/cakephp-attachment 包。
此包的最新版本(4.0.1.2)没有可用的许可证信息。

CakePHP 附件插件

维护者

详细信息

github.com/3xw/attachment

源代码

问题

安装次数: 1,139

依赖者: 3

推荐者: 0

安全: 0

星标: 1

关注者: 3

分支: 0

公开问题: 3

类型:cakephp-plugin

4.0.1.2 2023-02-27 15:01 UTC

This package is auto-updated.

Last update: 2024-01-25 11:26:35 UTC


README

请使用 3xw/cakephp-attachment 代替!!

CakePHP ^3.7 附件插件

附件插件解决了媒体、文件和嵌入数据的一些常见问题。目标是存储你想要的地方( Dropbox、AWS S3、... )并在表中记录。

附件提供存储层、数据库层以及前端和后端解决方案,以满足常见需求。

它使用 CakePHP 3FlysystemIntervention Image

安装

安装.composer

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方法是

composer require 3xw/attachment

安装.load

在 src/Application.php 中

$this->addPlugin(\ Attachment\Plugin::class, ['bootstrap' => true, 'routes' => true]);

或者,你可以用你自己的设置覆盖它(config/attachment.php)

Configure::write('Attachment.config', ['attachment']);
$this->addPlugin(\ Attachment\Plugin::class, ['bootstrap' => true, 'routes' => true]);

安装.db

bin/cake Migrations migrate -p Attachment

一个 sql 文件可以在以下路径找到

vendor/3xw/attachment/config/Schema/attachment.sql

安装.folders

创建一个缩略图文件夹,并使用适当的 chmod 以允许 php 向其中写入...

mkdir webroot/thumbnails
chmod 777 webroot/thumbnails

如果您在本地上存储文件,则根据默认设置或您自己的设置创建一个文件夹。默认设置如下

mkdir webroot/files
chmod 777 webroot/files

后端依赖项

后端依赖项.libs

为了使用后端工具,您需要安装以下库

javascript

jquery >= 1.x
vuejs = 2.x
vue-resource = 1.x

css

bootstrap = 4.x

后端依赖项.html

Vuejs 组件嵌套在一个顶层父组件中,你需要设置它。它需要一个额外的块(模板)。以下是一个简单的方法。

在你的 layout.ctp 中

<head>
	...
	<!-- CSS -->
	<?= $this->Html->css([
	    'bootstrap.min.css',
	    'app.css'
  	]) ?>
	<?= $this->fetch('css') ?>
	...
</head>
<body>
	<div id="admin-app" class="wrapper">
		...flash, content goes here...
	</div>

	<!-- TEMPLATES -->
	<?= $this->fetch('template') ?>

	<!-- SCRIPTS -->
	<?= $this->Html->script([
	    'jquery.min.js'
	    'vue.min.js',
	    'vue-resource.min.js',
	    'app.js'
	 ]) ?>
	<?= $this->fetch('script') ?>

</body>

后端依赖项.js

在你的 app.js 中

(function(scope, $, Vue){

	// boostrap
	$(document).ready(function(){ var adminApp = new Vue({el: "#admin-app"}) })


})(window, jQuery, Vue)

设置

默认设置位于以下路径:vendor/3xw/attachment/config/attachment.php

你可以在以下路径创建自己的设置:config/attachment.php

设置示例

return [
  'Attachment' => [

    // set profiles
    'profiles' => [
      's3' => [
		'replace' => false,
		'afterReplace' => null // null | callback fct($entity),
		'delete' => true,
		'adapter' => 'League\Flysystem\AwsS3v3\AwsS3Adapter',
		'client' => new League\Flysystem\AwsS3v3\AwsS3Adapter(Aws\S3\S3Client::factory([
			'credentials' => [
				'key'    => '***',
				'secret' => '***',
			],
			'region' => 'eu-central-1',
			'version' => 'latest',
		]),'s3.example.com',''),
		'baseUrl' =>  's3.example.com'
      ],
    ],

    // lsiteners
    lsiteners => [],

    // upload settings
    'upload' => [
      'maxsize' => 30, // 30MB
      'types' =>['image/jpeg','image/png','image/gif'],
      'atags' => [],
      'atagsDisplay' => false, // false | 'select' | 'input'
      'profile' => 's3',

      // pagination setting in browse views
      'pagination' => [
        'offset' => 9, // = 10 pages
        'start' => true,
        'end' => true,
      ],
    ],

    // thumbnails settings
    'thumbnails' => [
      'driver' => 'Imagick', // or Imagick if installed,
      'compression' => [
     		'jpegoptim' => '/usr/local/bin/jpegoptim', // path or false ( default /usr/local/bin/jpegoptim )
    		'pngquant' => '/usr/local/bin/pngquant', // path or false ( default /usr/local/bin/pngquant )
    		'quality' => 25 // encoding quality level from 0 to 100 ( default 25 )
  		],
  		'breakpoints' => [
	        'lg' => '(min-width: 1200px)',
	        'md' => '(max-width: 1199px)',
	        'sm' => '(max-width: 991px)',
	        'xs' => '(max-width: 767px)',
      ],
      'widths' => ['678','1200'],
      'heights' => false,
      'aligns' => false, // or some of following [0,1,2,3,4,5,6,7,8] with 0 center, 1 top, 4 left, 5 right top corner, 8 left top corner ....
      'crops' => ['16:9','4:3','1:1']
    ]
]];

设置.profiles

您可以根据 Flysystem 文档设置您的配置文件,只需添加 baseUrl 以获取完整 URL。配置文件按名称存储。因此,您可以将文件拆分到多个系统中。

附件默认包含三个设置。

default // Local file system stored in webroot/files
external // used for external urls
cache // for thumbs creations

以下为本地存储的默认适配器。

'default' => [
	'adapter' => 'League\Flysystem\Adapter\Local',
	'client' => new League\Flysystem\Adapter\Local('files'),
	'baseUrl' =>  '/files/'
],

因此,您可以使用自己的或使用 composer 安装新的适配器。

Settings.upload

在保存相关记录之前会进行上传操作。全局设置在 Attachment.upload 下配置。您可以在 add.ctp 或 edit.ctp 中设置全局行为,并在本地覆盖它们。这里有多种选项可用。

'upload' => [
  'maxsize' => 30, // 30MB
  'types' =>['image/jpeg','embed/soundcloud',...], // mime types and embed/:service for embed stuff
  'atags' => [], // atags are use to store attachemnts with
  'relation' => 'belongsToMany', // model relation
  'profile' => 'default', // profile to use (where you store files)
  'visibility' => 'public', // public or private
  'speech' => false, // french goody
  'restrictions' => [] // or Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED
],

限制是在后端中用于排序文件的策略。

AttachmentHelper::TAG_RESTRICTED // enforce attachments to associted with given tags in save and retieve with a AND strategy
AttachmentHelper::TAG_OR_RESTRICTED // enforce attachments to associted with given tags in save and retieve with a OR strategy
AttachmentHelper::types_restricted // enforce attachments to saved and retrieve with a OR strategy according given mime types

Settings.listeners

监听器是执行相关事件触发时执行的处理器。您可以在附件配置文件中设置通用处理器,或者您可以将 'listeners' 键添加到任何具有 CRUD 能力的附件辅助函数的设置数组中。

'listeners' => [
  'beforePaginate' => [
    'App\Listener\MyListener',
    'App\Listener\MayOtherListener' => [
      'momo' => 'toto'
    ]
  ],
]

触发的事件列表如下。

beforeFilter
startup
beforeDelete
afterDelete
beforeFind
afterFind
beforeSave
afterSave
beforePaginate
afterPaginate
beforeRedirect
beforeRender
recordNotFound
setFlash

监听器应扩展 BaseListener 类。

namespace App\Listener;

use Attachment\Listener\BaseListener;
use Cake\Event\Event;

class ExtranetMoveFileListener extends BaseListener
{
  // $event->getSubject() returns an object with minimum a request variable
  // all model events are wrapped on top of:
  // https://crud.readthedocs.io/en/latest/events.html#crud-beforesave
  public function respond(Event $event)  
  {

  }
}

Settings.thumbnails

Attachment.thumbnails 是缩略图生成的设置。

'thumbnails' => [
  'driver' => 'Imagick', // or Imagick if installed,
  'widths' => [600, 1200],
  'heights' => [],
  'aligns' => [], // or some of following [0,1,2,3,4,5,6,7,8] with 0 center, 1 top, 4 left, 5 right top corner, 8 left top corner ....
  'crops' => ['4:3','16:9']
]

这些设置是全局的,并限制本地更改以保持缩略图逻辑在单个文件中并限制额外格式。每个表都是您允许的可能性。因此,只有 600px 和 1200px 的缩略图被允许。仅允许 4:3 和 16:9 的裁剪。

用法

Usage.model

附件包括两个表:Attachments 和 Atags。因此,您可以将任何模型与之一一绑定,所有关系类型都受支持。

$this->belongsToMany('Attachments', [
  'foreignKey' => 'post_id',
  'targetForeignKey' => 'attachment_id',
  'joinTable' => 'attachments_posts'
]);

// OR

$this->belongsTo('Attachments', [
  'foreignKey' => 'attachment_id',
  'joinType' => 'INNER' // OR LEFT ...
]);

附件还处理 'order' 字段。因此,您可以在 HABTM 连接表中自由添加此类字段...

Usage.controller

简单地使用 contain 或任何需要的连接...

public function index()
{
	$this->paginate = [
	  'contain' => ['Attachments' /* => ['sort' => 'order'] */ ] // if HABTM with an order field
	];
	$posts = $this->paginate($this->Posts);
	$this->set(compact('posts'));
	$this->set('_serialize', ['posts']);
}

Usage.view

所有技能都在 Helper Attachment 中。因此,首先将其添加到您的 AppView。

在 src/View/AppView.php

public function initialize()
{
	$this->loadHelper('Attachment.Attachment');
}

Usage.view.backend

在 add.ctp

<!-- Attachment -->
<?= $this->Attachment->input('Attachments', // if Attachments => HABTM else if !Attachments => belongsTo
  	[
	  	'label' => 'Image',
	  	'types' =>['image/jpeg','image/png'],
	  	'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
	  	'profile' => 's3', // optional as it was set in config/attachment.php
	  	'cols' => 'col-xs-6 col-md-6 col-lg-4', // optional as it was set in config/attachment.php,
	  	'maxquantity' => -1,
	  	'restrictions' => [
	    	Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
	    	Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
	  	],
	  	'attachments' => [] // array of exisiting Attachment entities ( HABTM ) or [entity] ( belongsTo )
	]
) ?>

在 edit.ctp

<!-- Attachment -->
<?= $this->Attachment->input('Attachments', // if Attachments => HABTM else if !Attachments => belongsTo
  	[
	  	'label' => 'Image',
	  	'types' =>['image/jpeg','image/png'],
	  	'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
	  	'profile' => 's3', // optional as it was set in config/attachment.php
	  	'cols' => 'col-xs-6 col-md-6 col-lg-4', // optional as it was set in config/attachment.php,
	  	'maxquantity' => -1,
	  	'restrictions' => [
	    	Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
	    	Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
	  	],
	  	'attachments' => $posts->attachments // array of exisiting Attachment entities ( HABTM ) or entity ( belongsTo )
	]
) ?>
全局附件索引
<!-- Attachments element -->
<?= $this->Attachment->buildIndex([
  'actions' => ['add','edit','delete','view','download'],
  'types' =>['image/jpeg','image/png','embed/youtube','embed/vimeo'],
  'atags' => ['Restricted Tag 1', 'Restricted Tag 2'],
		'listStyle' => true,
		'profile' => 's3', // optional as it was set in config/attachment.php
  'restrictions' => [
    Attachment\View\Helper\AttachmentHelper::TAG_RESTRICTED,
    Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
  ]
]) ?>
TinyMCE 插件

附件附带一个 TinyMCE 插件。与 cakephp-tinymce 包包一起使用。

echo $this->element('Trois/Tinymce.tinymce',[
  'field' => 'content',
  'value' => $post->content,
  'init' => [
    'external_plugins' => [
      'attachment' => $this->Url->build('/attachment/js/Plugins/tinymce/plugin.min.js', true),
    ],
    'attachment_settings' => $this->Attachment->jsSetup('content',[

      // overrides config/attachment.php settings
      'types' => [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/jpeg',
        'image/png',
        'embed/youtube',
        'embed/vimeo'
      ],
			'thumbBaseUrl' => '', //IF NOT $this->Url->build('/')
      'atags' => [],
      'restrictions' => [
        Attachment\View\Helper\AttachmentHelper::TAG_OR_RESTRICTED,
        Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
      ],
    ])
  ]
]);

这将让您直接在 trumbowyg 文本区域中插入图像!!! 嘿嘿!

在 locale.ctp 中的示例

$this->element('locale',['fields' => ['meta',
	'header' => [
		'Trois/Tinymce.tinymce' => [
			'value' => $post,
			'init' => []
		]
	],
	'body' => [
		'Trois/Tinymce.tinymce' => [
			'value' => $post,
			'init' => [
				'external_plugins' => [
					'attachment' => $this->Url->build('/attachment/js/Plugins/tinymce/plugin.min.js', true),
				],
				'attachment_settings' => [
					'types' => [
						'application/pdf',
						'application/msword',
						'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
						'application/vnd.ms-excel',
						'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
						'image/jpeg',
						'image/png',
						'embed/youtube',
						'embed/vimeo'
					],
					'atags' => [],
					'restrictions' => [
						Attachment\View\Helper\AttachmentHelper::TAG_OR_RESTRICTED,
						Attachment\View\Helper\AttachmentHelper::TYPES_RESTRICTED
					],
				]
			]
		]
	]
], 'labels' => ['meta (description google, facebook)', 'lead', 'text']]);

Usage.view.frontend

在文件中

<!-- Display a 16:9 croped image  -->
<?= $this->Attachment->image([
	'image' => $post->attachments[0]->path,
	'profile' => $post->attachments[0]->profile,
	'width' => '600',
	'cropratio' => '16:9,
	'quality' => 50, // from 0 to 100 ( default 25 in plugin's config file attachment.php )
	'srcset' => [
      'lg' => [360,720],
      'md' => [293, 586],
      'sm' => [283, 566],
      'xs' => [767,1534],
    ]
],['class' => 'img-responsive']) ?>

<!-- Display an embed video  -->
<?= $post->attachments[0]->embed ?>

仅 URL

<?= $this->Attachment->thumbSrc([
	'image' => $post->attachments[0]->path,
	'profile' => $post->attachments[0]->profile,
	'width' => '600',
	'cropratio' => '16:9,
	'quality' => 50, // from 0 to 100 ( default 25 in plugin's config file attachment.php )
	'srcset' => [
      'lg' => [360,720],
      'md' => [293, 586],
      'sm' => [283, 566],
      'xs' => [767,1534],
    ]
]) ?>

Usage.view.download

echo $this->Attachment->downloadLink($attachment ); // Attachment $attachment
// return the full download url for THIS SESSION ONLY

Usage.shell

  1. 附件插件提供了一个有用的 shell 脚本,用于检索图像的宽度和高度。
bin/cake Attachment.GetImageSizes
  1. 为本地创建缺失的附件翻译
bin/cake CreateMissingTranslations en_GB de_CH ...