イントロダクションIntroduction
LaravelはFrank de Jongeさんが作成した拝みたいほど素晴らしい、抽象ファイルシステムであるFlysystem PHPパッケージを提供しています。LaravelとFlysystemの統合によりローカルのファイルシステム、Amazon S3、Rackspaceクラウドストレージを操作できる、シンプルなドライバが提供できました。更に素晴らしいことにそれぞれのシステムに対し同じAPIを使用しているため、ストレージをとても簡単に変更できるのです。Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem[https://github.com/thephpleague/flysystem] PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.
設定Configuration
ファイルシステムの設定ファイルは、config/filesystems.php
です。このファイルの中に全「ディスク」の設定があります。それぞれのディスクは特定のストレージドライバと保存場所を表します。設定ファイルにはサポート済みのドライバそれぞれの設定例を用意しています。ですからストレージの設定と認証情報を反映するように、設定オプションを簡単に修正できます。The filesystem configuration file
is located at config/filesystems.php
.
Within this file you may configure all of your
"disks". Each disk represents a particular
storage driver and storage location. Example
configurations for each supported driver are
included in the configuration file. So, modify the
configuration to reflect your storage preferences
and credentials.
好きなだけディスクを設定できますし、同じドライバに対し複数のディスクを持つことも可能です。You may configure as many disks as you like, and may even have multiple disks that use the same driver.
パブリックディスクThe Public Disk
public
ディスクは一般公開へのアクセスを許すファイルを意味しています。デフォルトのpublic
ディスクは、local
ドライバを使用しており、storage/app/public
下に存在しているファイルです。Webからのアクセスを許すには、public/storage
からstorage/app/public
へシンボリックリンクを張る必要があります。この手法により、公開ファイルを一つのディレクトリへ留め、Envoyerのようなリリース時のダウンタイムが起きない開発システムを使っている場合、各リリース間でファイルを簡単に共有できます。The public
disk is
intended for files that are going to be publicly
accessible. By default, the public
disk
uses the local
driver and stores these
files in storage/app/public
. To make
them accessible from the web, you should create a
symbolic link from public/storage
to
storage/app/public
. This convention
will keep your publicly accessible files in one
directory that can be easily shared across
deployments when using zero down-time deployment
systems like
Envoyer[https://envoyer.io].
シンボリックリンクを張るには、storage:link
Artisanコマンドを使用します。To create the
symbolic link, you may use the
storage:link
Artisan
command:
php artisan storage:link
ファイルを保存し、シンボリックリンクを張ったら、asset
ヘルパを使いファイルへのURLを生成できます。Once a file has been stored and
the symbolic link has been created, you can create a
URL to the files using the asset
helper:
echo asset('storage/file.txt');
ローカルディスクThe Local Driver
local
ドライバを使う場合、filesystems
設定ファイルで指定したroot
ディレクトリからの相対位置で全ファイル操作が行われることに注意してください。デフォルトでこの値はstorage/app
ディレクトリに設定されています。そのため次のメソッドでファイルはstorage/app/file.txt
として保存されます。When using the local
driver, all file operations are relative to the
root
directory defined in your
filesystems
configuration file. By
default, this value is set to the
storage/app
directory. Therefore, the
following method would store a file in
storage/app/file.txt
:
Storage::disk('local')->put('file.txt', 'Contents');
パーミッションPermissions
public
下のパーミッションは、ディレクトリへ0755
、ファイルへ0664
を設定します。パーミッションはfilesystems
設定ファイルで変更可能です。The public
visibility[#file-visibility] translates to
0755
for directories and
0644
for files. You can modify the
permissions mappings in your
filesystems
configuration
file:
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'permissions' => [
'file' => [
'public' => 0664,
'private' => 0600,
],
'dir' => [
'public' => 0775,
'private' => 0700,
],
],
],
ドライバ要件Driver Prerequisites
ComposerパッケージComposer Packages
SFTPやS3、Rackspaceドライバを使用する場合は、それに適合するパッケージをComposerでインストールする必要があります。Before using the SFTP, S3, or Rackspace drivers, you will need to install the appropriate package via Composer:
- SFTP:
league/flysystem-sftp ~1.0
SFTP:league/flysystem-sftp ~1.0
- Amazon S3:
league/flysystem-aws-s3-v3 ~1.0
Amazon S3:league/flysystem-aws-s3-v3 ~1.0
- Rackspace:
league/flysystem-rackspace ~1.0
Rackspace:league/flysystem-rackspace ~1.0
パフォーマンスを上げるため、絶対に必要なのはキャッシュアダプタです。そのためには、追加のパッケージが必要です。An absolute must for performance is to use a cached adapter. You will need an additional package for this:
- CachedAdapter:
league/flysystem-cached-adapter ~1.0
CachedAdapter:league/flysystem-cached-adapter ~1.0
S3ドライバ設定S3 Driver Configuration
S3ドライバの設定情報は、config/filesystems.php
設定ファイルにあります。このファイルはS3ドライバの設定配列のサンプルを含んでいます。この配列を自由に、自分のS3設定と認証情報に合わせて、変更してください。使いやすいように、環境変数はAWSで使用されている命名規約に合わせてあります。The S3 driver
configuration information is located
in your
config/filesystems.php
configuration file. This file
contains an example configuration
array for an S3 driver. You are free
to modify this array with your own
S3 configuration and credentials.
For convenience, these environment
variables match the naming
convention used by the AWS
CLI.
FTPドライバ設定FTP Driver Configuration
Laravelのファイルシステム統合はFTPでも動作します。しかし、デフォルトでは、フレームワークのfilesystems.php
設定ファイルに、サンプルの設定を含めていません。FTPファイルシステムを設定する必要がある場合は、以下の設定例を利用してください。Laravel's
Flysystem integrations works great
with FTP; however, a sample
configuration is not included with
the framework's default
filesystems.php
configuration file. If you need to
configure a FTP filesystem, you may
use the example configuration
below:
'ftp' => [
'driver' => 'ftp',
'host' => 'ftp.example.com',
'username' => 'your-username',
'password' => 'your-password',
// FTP設定のオプション
// 'port' => 21,
// 'root' => '',
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
SFTPドライバ設定SFTP Driver Configuration
Laravelのファイルシステム統合はSFTPできちんと動作します。しかし、デフォルトでは、フレームワークのfilesystems.php
設定ファイルに、サンプルの設定を含めていません。SFTPファイルシステムを設定する必要がある場合は、以下の設定例を利用してください。Laravel's
Flysystem integrations works great
with SFTP; however, a sample
configuration is not included with
the framework's default
filesystems.php
configuration file. If you need to
configure a SFTP filesystem, you may
use the example configuration
below:
'sftp' => [
'driver' => 'sftp',
'host' => 'example.com',
'username' => 'your-username',
'password' => 'your-password',
// SSH keyベースの認証の設定
// 'privateKey' => '/path/to/privateKey',
// 'password' => 'encryption-password',
// FTP設定のオプション
// 'port' => 22,
// 'root' => '',
// 'timeout' => 30,
],
Rackspaceドライバ設定Rackspace Driver Configuration
Laravelのファイルシステム統合はRackspaceでも動作します。しかし、デフォルトでは、フレームワークのfilesystems.php
設定ファイルに、サンプルの設定を含めていません。Rackspaceファイルシステムを設定する必要がある場合は、以下の設定例を利用してください。Laravel's
Flysystem integrations works great
with Rackspace; however, a sample
configuration is not included with
the framework's default
filesystems.php
configuration file. If you need to
configure a Rackspace filesystem,
you may use the example
configuration below:
'rackspace' => [
'driver' => 'rackspace',
'username' => 'your-username',
'key' => 'your-key',
'container' => 'your-container',
'endpoint' => 'https://identity.api.rackspacecloud.com/v2.0/',
'region' => 'IAD',
'url_type' => 'publicURL',
],
キャッシュCaching
特定のディスクでキャッシュを有効にするには、ディスクの設定オプションに、cache
ディレクティブを追加してください。cache
オプションは、disk
名、expire
期間を秒数、キャッシュのprefix
を含むオプションの配列です。To enable caching
for a given disk, you may add a
cache
directive to the
disk's configuration options. The
cache
option should be
an array of caching options
containing the disk
name, the expire
time
in seconds, and the cache
prefix
:
's3' => [
'driver' => 's3',
// Other Disk Options...
'cache' => [
'store' => 'memcached',
'expire' => 600,
'prefix' => 'cache-prefix',
],
],
ディスクインスタンス取得Obtaining Disk Instances
Storage
ファサードを使い設定済みのディスクへの操作ができます。たとえばこのファサードのput
メソッドを使用し、デフォルトディスクにアバターを保存できます。Storage
ファサードのメソッド呼び出しで最初にdisk
メソッドを呼び出さない場合、そのメソッドの呼び出しは自動的にデフォルトディスクに対し実行されます。The
Storage
facade may be
used to interact with any of your
configured disks. For example, you
may use the put
method
on the facade to store an avatar on
the default disk. If you call
methods on the Storage
facade without first calling the
disk
method, the method
call will automatically be passed to
the default disk:
use Illuminate\Support\Facades\Storage;
Storage::put('avatars/1', $fileContents);
複数ディスクを使用する場合、Storage
ファサードのdisk
メソッドを使用し特定のディスクへアクセスできます。If your
application interacts with multiple
disks, you may use the
disk
method on the
Storage
facade to work
with files on a particular
disk:
Storage::disk('s3')->put('avatars/1', $fileContents);
ファイル取得Retrieving Files
get
メソッドは指定したファイルの内容を取得するために使用します。ファイル内容がそのまま、メソッドより返されます。ファイルパスはすべて、ディスクに設定した「ルート(root)」からの相対位置で指定することを思い出してください。The
get
method may be used
to retrieve the contents of a file.
The raw string contents of the file
will be returned by the method.
Remember, all file paths should be
specified relative to the
"root" location configured
for the disk:
$contents = Storage::get('file.jpg');
exists
メソッドは指定したディスクにファイルが存在しているかを判定するために使用します。The
exists
method may be
used to determine if a file exists
on the disk:
$exists = Storage::disk('s3')->exists('file.jpg');
ファイルのダウンロードDownloading Files
download
メソッドは、指定したパスへファイルをダウンロードするように、ユーザーのブラウザへ強制するレスポンスを生成するために使用します。download
メソッドはファイル名を第2引数として受け取り、ダウンロード先のファイル名を指定します。最後に第3引数として、HTTPヘッダの配列を渡せます。The
download
method may be
used to generate a response that
forces the user's browser to
download the file at the given path.
The download
method
accepts a file name as the second
argument to the method, which will
determine the file name that is seen
by the user downloading the file.
Finally, you may pass an array of
HTTP headers as the third argument
to the method:
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);
ファイルURLFile URLs
指定したファイルのURLを取得するには、url
メソッドを使います。local
ドライバを使用している場合、通常このメソッドは指定したパスの先頭に/storage
を付け、そのファイルへの相対パスを返します。s3
、もしくはrackspace
ドライバを使用している場合、完全なリモートURLを返します。You may use the
url
method to get the
URL for the given file. If you are
using the local
driver,
this will typically just prepend
/storage
to the given
path and return a relative URL to
the file. If you are using the
s3
or
rackspace
driver, the
fully qualified remote URL will be
returned:
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg');
Note:
local
ドライバを使用する場合、一般公開するファイルはすべて、storage/app/public
ディレクトリへ設置する必要があることを忘れないでください。さらに、public/storage
からstorage/app/public
ディレクトリへシンボリックリンクを張る必要もあります。{note} Remember, if you are using thelocal
driver, all files that should be publicly accessible should be placed in thestorage/app/public
directory. Furthermore, you should create a symbolic link[#the-public-disk] atpublic/storage
which points to thestorage/app/public
directory.
一時的なURLTemporary URLs
s3
、もしくはrackspace
ドライバを使用して保存したファイルに対し、指定ファイルの一時的なURLを作成する場合は、temporaryUrl
メソッドを使用します。このメソッドはパスと、URLの有効期限を指定するDateTime
インスタンスを引数に取ります。For files stored
using the s3
or
rackspace
driver, you
may create a temporary URL to a
given file using the
temporaryUrl
method.
This methods accepts a path and a
DateTime
instance
specifying when the URL should
expire:
$url = Storage::temporaryUrl(
'file.jpg', now()->addMinutes(5)
);
追加のS3リクエストパラメータを指定する必要がある場合は、temporaryUrl
メソッドの第3引数へリクエストパラメータの配列を渡してください。If you need to
specify additional S3 request
parameters[https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html#RESTObjectGET-requests],
you may pass the array of request
parameters as the third argument to
the temporaryUrl
method:
$url = Storage::temporaryUrl(
'file.jpg',
now()->addMinutes(5),
['ResponseContentType' => 'application/octet-stream']
);
ローカルURLホストカスタマイズLocal URL Host Customization
local
ドライバを使用し、ディスク上に保存されるファイルのホストを事前定義したい場合は、ディスク設定配列へurl
オプションを追加してください。If you would like
to pre-define the host for files
stored on a disk using the
local
driver, you may
add a url
option to the
disk's configuration
array:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
ファイルメタ情報File Metadata
ファイルの読み書きに加え、Laravelはファイル自体に関する情報も提供します。たとえば、size
メソッドはファイルサイズをバイトで取得するために、使用します。In addition to
reading and writing files, Laravel
can also provide information about
the files themselves. For example,
the size
method may be
used to get the size of the file in
bytes:
use Illuminate\Support\Facades\Storage;
$size = Storage::size('file.jpg');
lastModified
メソッドは最後にファイルが更新された時のUnixタイムスタンプを返します。The
lastModified
method
returns the UNIX timestamp of the
last time the file was
modified:
$time = Storage::lastModified('file.jpg');
ファイル保存Storing Files
put
メソッドはファイル内容をディスクに保存するために使用します。put
メソッドにはPHPのresource
も渡すことができ、Flysystemの裏で動いているストリームサポートを使用します。大きなファイルを取り扱う場合は、ストリームの使用を強く推奨します。The
put
method may be used
to store raw file contents on a
disk. You may also pass a PHP
resource
to the
put
method, which will
use Flysystem's underlying stream
support. Using streams is greatly
recommended when dealing with large
files:
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents);
Storage::put('file.jpg', $resource);
自動ストリーミングAutomatic Streaming
指定したファイル位置のファイルのストリーミングを自動的にLaravelに管理させたい場合は、putFile
かputFileAs
メソッドを使います。このメソッドは、Illuminate\Http\File
かIlluminate\Http\UploadedFile
のインスタンスを引数に取り、希望する場所へファイルを自動的にストリームします。If you would like
Laravel to automatically manage
streaming a given file to your
storage location, you may use the
putFile
or
putFileAs
method. This
method accepts either a
Illuminate\Http\File
or
Illuminate\Http\UploadedFile
instance and will automatically
stream the file to your desired
location:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// 自動的に一意のIDがファイル名として指定される
Storage::putFile('photos', new File('/path/to/photo'));
// ファイル名を指定する
Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');
putFile
メソッドにはいくつか重要な注意点があります。ファイル名ではなく、ディレクトリ名を指定することに注意してください。putFile
メソッドは一意のIDを保存ファイル名として生成します。ファイルの拡張子は、MIMEタイプの検査により決まります。putFile
メソッドからファイルへのパスが返されますので、生成されたファイル名も含めたパスをデータベースへ保存することができます。There are a few
important things to note about the
putFile
method. Note
that we only specified a directory
name, not a file name. By default,
the putFile
method will
generate a unique ID to serve as the
file name. The file's extension will
be determined by examining the
file's MIME type. The path to the
file will be returned by the
putFile
method so you
can store the path, including the
generated file name, in your
database.
putFile
とputFileAs
メソッドはさらに、保存ファイルの「視認性」を指定する引数も受け付けます。これは特にS3などのクラウドディスクにファイルを保存し、一般公開の視認性を設定したい場合に便利です。The
putFile
and
putFileAs
methods also
accept an argument to specify the
"visibility" of the stored
file. This is particularly useful if
you are storing the file on a cloud
disk such as S3 and would like the
file to be publicly
accessible:
Storage::putFile('photos', new File('/path/to/photo'), 'public');
ファイルの先頭/末尾への追加Prepending & Appending To Files
prepend
とappend
メソッドで、ファイルの初めと終わりに内容を追加できます。The
prepend
and
append
methods allow
you to write to the beginning or end
of a file:
Storage::prepend('file.log', 'Prepended Text');
Storage::append('file.log', 'Appended Text');
ファイルコピーと移動Copying & Moving Files
copy
メソッドは、存在するファイルをディスク上の新しい場所へコピーするために使用します。一方のmove
メソッドはリネームや存在するファイルを新しい場所へ移動するために使用します。The
copy
method may be used
to copy an existing file to a new
location on the disk, while the
move
method may be used
to rename or move an existing file
to a new location:
Storage::copy('old/file.jpg', 'new/file.jpg');
Storage::move('old/file.jpg', 'new/file.jpg');
ファイルアップロードFile Uploads
Webアプリケーションで、ファイルを保存する一般的なケースは、ユーザーがプロファイル画像や写真、ドキュメントをアップロードする場合でしょう。アップロードファイルインスタンスにstore
メソッドを使えば、アップロードファイルの保存はLaravelで簡単に行なえます。アップロードファイルを保存したいパスを指定し、store
メソッドを呼び出してください。In web
applications, one of the most common
use-cases for storing files is
storing user uploaded files such as
profile pictures, photos, and
documents. Laravel makes it very
easy to store uploaded files using
the store
method on an
uploaded file instance. Call the
store
method with the
path at which you wish to store the
uploaded file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserAvatarController extends Controller
{
/**
* ユーザーのアバターの更新
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
$path = $request->file('avatar')->store('avatars');
return $path;
}
}
この例には重要な点が含まれています。ファイル名ではなく、ディレクトリ名を指定している点に注目です。デフォルトでstore
メソッドは、一意のIDをファイル名として生成します。ファイルの拡張子は、MIMEタイプの検査により決まります。store
メソッドからファイルパスが返されますので、生成されたファイル名を含めた、そのファイルパスをデータベースに保存できます。There are a few
important things to note about this
example. Note that we only specified
a directory name, not a file name.
By default, the store
method will generate a unique ID to
serve as the file name. The file's
extension will be determined by
examining the file's MIME type. The
path to the file will be returned by
the store
method so you
can store the path, including the
generated file name, in your
database.
上の例と同じ操作を行うため、Storage
ファサードのputFile
メソッドを呼び出すこともできます。You may also call
the putFile
method on
the Storage
facade to
perform the same file manipulation
as the example above:
$path = Storage::putFile('avatars', $request->file('avatar'));
ファイル名の指定Specifying A File Name
保存ファイルが自動的に命名されたくなければ、ファイルパスとファイル名、(任意で)ディスクを引数に持つstoreAs
メソッドを使ってください。If you would not
like a file name to be automatically
assigned to your stored file, you
may use the storeAs
method, which receives the path, the
file name, and the (optional) disk
as its arguments:
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
上記の例と同じファイル操作を行う、Storage
ファサードのputFileAs
メソッドも使用できます。You may also use
the putFileAs
method on
the Storage
facade,
which will perform the same file
manipulation as the example
above:
$path = Storage::putFileAs(
'avatars', $request->file('avatar'), $request->user()->id
);
Note:
印刷できない、または無効なユニコードは自動的にファイルパスから削除されます。そのため、Laravelのファイルストレージメソッドに渡す前に、ファイルパスをサニタライズしましょう。ファイルパスのノーマライズは、League\Flysystem\Util::normalizePath
メソッドを使います。{note} Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using theLeague\Flysystem\Util::normalizePath
method.
ディスクの指定Specifying A Disk
デフォルトで、store
メソッドはデフォルトディスクを使用します。他のディスクを指定したい場合は第2引数として、ディスク名を渡してください。By default, this
method will use your default disk.
If you would like to specify another
disk, pass the disk name as the
second argument to the
store
method:
$path = $request->file('avatar')->store(
'avatars/'.$request->user()->id, 's3'
);
ファイル視認性File Visibility
LaravelのFlysystem統合では、複数のプラットフォームにおけるファイルパーミッションを「視認性」として抽象化しています。ファイルはpublic
かprivate
のどちらかとして宣言します。ファイルをpublic
として宣言するのは、他からのアクセスを全般的に許可することを表明することです。たとえば、S3ドライバ使用時には、public
ファイルのURLを取得することになります。In Laravel's
Flysystem integration,
"visibility" is an
abstraction of file permissions
across multiple platforms. Files may
either be declared
public
or
private
. When a file is
declared public
, you
are indicating that the file should
generally be accessible to others.
For example, when using the S3
driver, you may retrieve URLs for
public
files.
put
メソッドでファイルをセットする時に、視認性を設定できます。You can set the
visibility when setting the file via
the put
method:
use Illuminate\Support\Facades\Storage;
Storage::put('file.jpg', $contents, 'public');
もし、ファイルが既に保存済みであるなら、getVisibility
とsetVisibility
により、視認性を取得/設定できます。If the file has
already been stored, its visibility
can be retrieved and set via the
getVisibility
and
setVisibility
methods:
$visibility = Storage::getVisibility('file.jpg');
Storage::setVisibility('file.jpg', 'public')
ファイル削除Deleting Files
delete
メソッドはディスクから削除するファイルを単独、もしくは配列で受け付けます。The
delete
method accepts a
single filename or an array of files
to remove from the disk:
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg');
Storage::delete(['file.jpg', 'file2.jpg']);
必要であれば、削除先のディスクを指定できます。If necessary, you may specify the disk that the file should be deleted from:
use Illuminate\Support\Facades\Storage;
Storage::disk('s3')->delete('folder_path/file_name.jpg');
ディレクトリDirectories
ディレクトリの全ファイル取得Get All Files Within A Directory
files
メソッドは指定したディレクトリの全ファイルの配列を返します。指定したディレクトリのサブディレクトリにある全ファイルのリストも取得したい場合は、allFiles
メソッドを使ってください。The
files
method returns an
array of all of the files in a given
directory. If you would like to
retrieve a list of all files within
a given directory including all
sub-directories, you may use the
allFiles
method:
use Illuminate\Support\Facades\Storage;
$files = Storage::files($directory);
$files = Storage::allFiles($directory);
ディレクトリの全ディレクトリ取得Get All Directories Within A Directory
directories
メソッドは指定したディレクトリの全ディレクトリの配列を返します。指定したディレクトリ下の全ディレクトリと、サブディレクトリ下の全ディレクトリも取得したい場合は、allDirectories
メソッドを使ってください。The
directories
method
returns an array of all the
directories within a given
directory. Additionally, you may use
the allDirectories
method to get a list of all
directories within a given directory
and all of its
sub-directories:
$directories = Storage::directories($directory);
// 再帰的
$directories = Storage::allDirectories($directory);
ディレクトリ作成Create A Directory
makeDirectory
メソッドは必要なサブディレクトリを含め、指定したディレクトリを作成します。The
makeDirectory
method
will create the given directory,
including any needed
sub-directories:
Storage::makeDirectory($directory);
ディレクトリ削除Delete A Directory
最後に、deleteDirectory
メソッドは、ディレクトリと中に含まれている全ファイルを削除するために使用されます。Finally, the
deleteDirectory
method
may be used to remove a directory
and all of its files:
Storage::deleteDirectory($directory);
カスタムファイルシステムCustom Filesystems
LaravelのFlysystem統合には、最初から様々な「ドライバ」が含まれています。しかしFlysystemはこれらのドライバに限定されず、他の保存領域システムにも適用できます。皆さんのLaravelアプリケーションに適合した保存システムのカスタムドライバを作成することができます。Laravel's Flysystem integration provides drivers for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application.
カスタムファイルシステムを準備するには、Flysystemアダプタが必要です。プロジェクトへコミュニティによりメンテナンスされているDropboxアダプタを追加してみましょう。In order to set up the custom filesystem you will need a Flysystem adapter. Let's add a community maintained Dropbox adapter to our project:
composer require spatie/flysystem-dropbox
次に、たとえばDropboxServiceProvider
のような、サービスプロバイダを用意してください。プロバイダのboot
メソッドの中でStorage
ファサードのextend
メソッドを使い、カスタムドライバを定義できます。Next, you should
create a service
provider[/docs/{{version}}/providers]
such as
DropboxServiceProvider
.
In the provider's boot
method, you may use the
Storage
facade's
extend
method to define
the custom driver:
<?php
namespace App\Providers;
use Storage;
use League\Flysystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
class DropboxServiceProvider extends ServiceProvider
{
/**
* コンテナ結合の登録
*
* @return void
*/
public function register()
{
//
}
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
Storage::extend('dropbox', function ($app, $config) {
$client = new DropboxClient(
$config['authorization_token']
);
return new Filesystem(new DropboxAdapter($client));
});
}
}
extend
メソッドの最初の引数はドライバの名前で、2つ目は$app
と$config
変数を受け取るクロージャです。このリゾルバークロージャはLeague\Flysystem\Filesystem
のインスタンスを返す必要があります。$config
変数はconfig/filesystems.php
で定義したディスクの値を含んでいます。The first
argument of the extend
method is the name of the driver and
the second is a Closure that
receives the $app
and
$config
variables. The
resolver Closure must return an
instance of
League\Flysystem\Filesystem
.
The $config
variable
contains the values defined in
config/filesystems.php
for the specified disk.
次に、config/app.php
設定ファイルで、サービスプロバイダを登録します。Next, register
the service provider in your
config/app.php
configuration file:
'providers' => [
// ...
App\Providers\DropboxServiceProvider::class,
];
拡張のサービスプロバイダを作成し、登録し終えたら、config/filesystems.php
設定ファイルで、dropbox
ドライバを使用します。Once you have
created and registered the
extension's service provider, you
may use the dropbox
driver in your
config/filesystems.php
configuration file.