diecoding/yii2-flysystem

为 Yii2 开发的本地和远程文件系统库,The League Flysystem

v1.6.3 2024-04-28 11:22 UTC

This package is auto-updated.

Last update: 2024-09-28 12:13:10 UTC


README

为 Yii2 开发的本地和远程文件系统库,The League Flysystem。

此扩展为 Yii 框架提供了 Flysystem 3 集成。 Flysystem 是一个文件系统抽象层,允许您轻松地将本地文件系统与远程文件系统进行交换。

Latest Stable Version Total Downloads Latest Stable Release Date Quality Score Build Status License PHP Version Require

Yii2 Flysystem 使用 league/flysystem

目录

安装

该软件包可在 Packagist 上获得,您可以使用 Composer 进行安装。

composer require diecoding/yii2-flysystem "^1.0"

或将以下内容添加到您的 composer.json 文件的 require 部分。

"diecoding/yii2-flysystem": "^1.0"

依赖项

开发依赖项

配置

本地文件系统

按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\LocalComponent::class,
            'path' => dirname(dirname(__DIR__)) . '/storage', // or you can use @alias
            'secret' => 'my-secret', // for secure route url
            // 'action' => '/site/file', // action route
            // 'prefix' => '',
        ],
    ],
];

AsyncAws S3 文件系统

或者运行

composer require league/flysystem-async-aws-s3:^3.0

或者添加

"league/flysystem-async-aws-s3": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\AsyncAwsS3Component::class,
            'endpoint' => 'http://your-endpoint',
            'bucket' => 'my-bucket',
            'accessKeyId' => 'my-key',
            'accessKeySecret' => 'my-secret',
            // 'sharedCredentialsFile' => '~/.aws/credentials',
            // 'sharedConfigFile' => '~/.aws/config',
            // 'region' => 'us-east-1',
            // 'endpointDiscoveryEnabled' => false,
            // 'pathStyleEndpoint' => false,
            // 'sendChunkedBody' => false,
            // 'debug' => false,
            // 'prefix' => '',
        ],
    ],
];

AWS S3 文件系统

或者运行

composer require league/flysystem-aws-s3-v3:^3.0

或者添加

"league/flysystem-aws-s3-v3": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\AwsS3Component::class,
            'endpoint' => 'http://your-endpoint',
            'key' => 'your-key',
            'secret' => 'your-secret',
            'bucket' => 'your-bucket',
            // 'region' => 'us-east-1'
            // 'version' => 'latest',
            // 'usePathStyleEndpoint' => false,
            // 'streamReads' => false,
            // 'options' => [],
            // 'credentials' => [],
            // 'debug' => false,
            // 'prefix' => '',
        ],
    ],
];

FTP 文件系统

或者运行

composer require league/flysystem-ftp:^3.0

或者添加

"league/flysystem-ftp": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\FtpComponent::class,
            'host' => 'hostname',
            'root' => '/root/path/', // or you can use @alias
            'username' => 'username',
            'password' => 'password',
            // 'port' => 21,
            // 'ssl' => false,
            // 'timeout' => 90,
            // 'utf8' => false,
            // 'passive' => true,
            // 'transferMode' => FTP_BINARY,
            // 'systemType' => null, // 'windows' or 'unix'
            // 'ignorePassiveAddress' => null, // true or false
            // 'timestampsOnUnixListingsEnabled' => false,
            // 'recurseManually' => true,
            // 'useRawListOptions' => null, // true or false
            // 'passphrase' => 'secret', // for secure route url
            // 'action' => '/site/file', // action route
            // 'prefix' => '',
        ],
    ],
];

SFTP 文件系统

或者运行

composer require league/flysystem-sftp-v3:^3.0

或者添加

"league/flysystem-sftp-v3": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        'fs' => [
            'class' => \diecoding\flysystem\SftpComponent::class,
            'host' => 'hostname',
            'username' => 'username',
            'password' => null, // password (optional, default: null) set to null if privateKey is used
            // 'privateKey' => '/path/to/my/private_key', // private key (optional, default: null) can be used instead of password, set to null if password is set
            // 'passphrase' => 'super-secret-password', // passphrase (optional, default: null), set to null if privateKey is not used or has no passphrase
            // 'port' => 22,
            // 'useAgent' => true,
            // 'timeout' => 10,
            // 'maxTries' => 4,
            // 'hostFingerprint' => null,
            // 'connectivityChecker' => null, // connectivity checker (must be an implementation of `League\Flysystem\PhpseclibV2\ConnectivityChecker` to check if a connection can be established (optional, omit if you don't need some special handling for setting reliable connections)
            // 'preferredAlgorithms' => [],
            // 'root' => '/root/path/', // or you can use @alias
            // 'action' => '/site/file', // action route
            // 'prefix' => '',
        ],
    ],
];

WebDAV 文件系统

或者运行

composer require league/flysystem-webdav:^3.0

或者添加

"league/flysystem-webdav": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\WebDavComponent::class,
            'baseUri' => 'http://your-webdav-server.org/',
            'userName' => 'your_user',
            'password' => 'superSecret1234',
            // 'proxy' => '',
            // 'authType' => \Sabre\DAV\Client::AUTH_BASIC,
            // 'encoding' => \Sabre\DAV\Client::ENCODING_IDENTITY,
            // 'prefix' => '',
        ],
    ],
];

ZipArchive 文件系统

或者运行

composer require league/flysystem-ziparchive:^3.0

或者添加

"league/flysystem-ziparchive": "^3.0"

到您的 composer.json 文件的 require 部分,并按照以下方式配置应用程序的 components

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            'class' => \diecoding\flysystem\ZipArchiveComponent::class,
            'pathToZip' => dirname(dirname(__DIR__)) . '/storage.zip', // or you can use @alias
            'secret' => 'my-secret', // for secure route url
            // 'action' => '/site/file', // action route
            // 'prefix' => '', // root directory inside zip file
        ],
    ],
];

其他配置

URL 文件操作设置

以下适配器具有生成 URL 文件操作的能力

  • 本地组件
  • FTP 组件
  • SFTP 组件

按照以下方式在 controller 中配置 action

此示例在 SiteController 中的 /site/file

class SiteController extends Controller
{
    //...
    public function actions()
    {
        return [
            // ...
            'file' => [
                'class' => \diecoding\flysystem\actions\FileAction::class,
                // 'component' => 'fs',
            ],
        ];
    }
}

请记住按照以下方式在 fs 应用程序组件中配置 action

return [
    // ...
    'components' => [
        // ...
        'fs' => [
            // ...
            'action' => '/site/file', // action for get url file
        ],
    ],
];

全局可见性设置

按照以下方式配置 fs 应用程序组件

return [
    //...
    'components' => [
        //...
        'fs' => [
            //...
            'config' => [
                'visibility' => \League\Flysystem\Visibility::PRIVATE,
            ],
        ],
    ],
];

用法

写入或更新文件

要写入或更新文件

Yii::$app->fs->write('filename.ext', 'contents');

使用流内容写入或更新文件

$stream = fopen('/path/to/somefile.ext', 'r+');
Yii::$app->fs->writeStream('filename.ext', $stream);

读取文件

读取文件

$contents = Yii::$app->fs->read('filename.ext');

获取读取流

$stream = Yii::$app->fs->readStream('filename.ext');
$contents = stream_get_contents($stream);
fclose($stream);

检查文件是否存在

检查文件是否存在

$exists = Yii::$app->fs->fileExists('filename.ext');

删除文件

删除文件

Yii::$app->fs->delete('filename.ext');

获取文件的 MIME 类型

获取文件 MIME 类型

$mimeType = Yii::$app->fs->mimeType('filename.ext');

获取文件的最后修改时间戳

获取文件时间戳

$timestamp = Yii::$app->fs->lastModified('filename.ext');

获取文件大小

获取文件大小

$byte = Yii::$app->fs->fileSize('filename.ext');

创建目录

创建目录

Yii::$app->fs->createDirectory('path/to/directory');

在写入更深路径时,目录也会隐式创建

Yii::$app->fs->write('path/to/filename.ext');

检查目录是否存在

检查目录是否存在

$exists = Yii::$app->fs->directoryExists('path/to/directory');

删除目录

删除目录

Yii::$app->fs->deleteDirectory('path/to/directory');

检查文件或目录是否存在

检查文件或目录是否存在

$exists = Yii::$app->fs->has('path/to/directory/filename.ext');

管理可见性

可见性是跨多个平台的文件权限的抽象。可见性可以是公共的或私有的。

Yii::$app->fs->write('filename.ext', 'contents', [
    'visibility' => \League\Flysystem\Visibility::PRIVATE
]);

您还可以更改和检查现有文件的可见性

if (Yii::$app->fs->visibility('filename.ext') === \League\Flysystem\Visibility::PRIVATE) {
    Yii::$app->fs->setVisibility('filename.ext', \League\Flysystem\Visibility::PUBLIC);
}

列出内容

列出内容

$contents = Yii::$app->fs->listContents();

foreach ($contents as $object) {
    echo $object['basename']
        . ' is located at' . $object['path']
        . ' and is a ' . $object['type'];
}

默认情况下,Flysystem 非递归地列出顶级目录。您可以通过提供目录名称和递归布尔值来获取更精确的结果

$contents = Yii::$app->fs->listContents('path/to/directory', true);

复制文件或目录

复制内容

Yii::$app->fs->copy('path/from/directory/filename.ext', 'path/to/directory/filename.ext', [
    'visibility' => \League\Flysystem\Visibility::PRIVATE
]);

移动文件或目录

移动内容

Yii::$app->fs->move('path/from/directory/filename.ext', 'path/to/directory/filename.ext', [
    'visibility' => \League\Flysystem\Visibility::PRIVATE
]);

获取 URL 文件

获取 URL 内容

Yii::$app->fs->publicUrl('path/to/directory/filename.ext');

获取临时文件或已签名 URL

获取临时 URL 内容

$expiresAt = new \DateTimeImmutable('+10 Minutes');

Yii::$app->fs->temporaryUrl('path/to/directory/filename.ext', $expiresAt);

$expiresAt 应该是一个有效的 PHP DateTimeInterface 实例。有关详细信息,请参阅 PHP 文档

获取 MD5 哈希文件内容

获取文件内容的 MD5 哈希值

Yii::$app->fs->checksum('path/to/directory/filename.ext');

使用特性

模型特性

将特质附加到包含将保存在 Flysystem (fs) 中的某些媒体属性的 Model/ActiveRecord

/**
 * @property string|null $file
 */
class Model extends \yii\db\ActiveRecord
{
    use \diecoding\flysystem\traits\ModelTrait;

    // ...

    public function rules()
    {
        return [
            ['image', 'string'], // Stores the filename
        ];
    }

    /**
     * @inheritdoc
     */
    protected function attributePaths()
    {
        return [
            'image' => 'images/'
        ];
    }

    // ...
}

覆盖 attributePaths() 方法以更改文件在 Flysystem (fs) 中保存的基本路径。

  • 您可以将不同的路径映射到您的 Model/ActiveRecord 的每个文件属性。

使用特性方法

$image = \yii\web\UploadedFile::getInstance($model, 'image');

// Save image_thumb.* to Flysystem (fs) on //my_bucket/images/ path
// The extension of the file will be determined by the submitted file type
// This allows multiple file types upload (png,jpg,gif,...)
// $model->image will hold "image_thumb.png" after this call finish with success
$model->saveUploadedFile($image, 'image', 'image_thumb');
$model->save();

// Save image_thumb.png to Flysystem (fs) on //my_bucket/images/ path
// The extension of the file will be determined by the submitted file type
// This force the extension to *.png
$model->saveUploadedFile($image, 'image', 'image_thumb.png', false);
$model->save();

// Remove the file with named saved on the image attribute
// Continuing the example, here "//my_bucket/images/my_image.png" will be deleted from Flysystem (fs)
$model->removeFile('image');
$model->save();

// Get the URL to the image on Flysystem (fs)
$model->getFileUrl('image');

// Get the presigned URL to the image on Flysystem (fs)
// The default duration is "+5 Minutes"
$model->getFilePresignedUrl('image');

重写特性方法

getFsComponent

Flysystem (fs) MediaTrait 依赖于此组件进行配置。默认配置是在索引 'fs' 上使用此组件,但您可以使用其他值。在这种情况下,覆盖 getFsComponent() 方法

public function getFsComponent()
{
    return Yii::$app->get('my_fs_component');
}
attributePaths

需要覆盖的主要方法是 attributePaths(),它为您的模型中的每个属性定义了 Flysystem (fs) 中的路径。这使得您可以在不同的 Flysystem (fs) 文件夹中保存每个属性。

以下是一个示例

protected function attributePaths()
{
    return [
        'logo' => 'logos/',
        'badge' => 'images/badges/'
    ];
}

// or use another attribute, example: id
// ! Note: id must contain a value first if you don't want it to be empty

protected function attributePaths()
{
    return [
        'logo' => 'thumbnail/' . $this->id . '/logos/',
        'badge' => 'thumbnail/' . $this->id . '/images/badges/'
    ];
}
getPresignedUrlDuration

默认的 URL 生成持续时间设置为 "+5 分钟",覆盖此方法并使用您自己的过期时间。返回必须为 DateTimeInterface 实例

protected function getPresignedUrlDuration($attribute)
{
    return new \DateTimeImmutable('+2 Hours');
}

// or if you want to set the attribute differently

protected function getPresignedUrlDuration($attribute)
{
    switch ($attribute) {
        case 'badge':
            return new \DateTimeImmutable('+2 Hours');
            break;
        
        default:
            return new \DateTimeImmutable('+1 Days');
            break;
    }
}

该值应该是一个有效的 PHP DateTimeInterface 实例。有关详细信息,请参阅 PHP 文档

阅读更多文档:https://sugengsulistiyawan.my.id/docs/opensource/yii2/flysystem/