Readouble

Laravel master ファイルシステム/クラウドストレージ

イントロダクション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, simply modify the configuration to reflect your storage preferences and credentials.

もちろん好きなだけディスクを設定できますし、同じドライバに対し複数のディスクを持つことも可能です。Of course, 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を生成できます。Of course, 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ドライバを使う場合、設定ファイルで指定したrootディレクトリからの相対位置で全ファイル操作が行われることに注意してください。デフォルトでこの値はstorage/appディレクトリに設定されています。そのため次のメソッドでファイルはstorage/app/file.txtとして保存されます。When using the local driver, all file operations are relative to the root directory defined in your 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');

ドライバ要件Driver Prerequisites

ComposerパッケージComposer Packages

S3とRackspaceドライバを使用する場合は、それに適合するパッケージをComposerでインストールする必要があります。Before using the S3 or Rackspace drivers, you will need to install the appropriate package via Composer:

  • Amazon S3: league/flysystem-aws-s3-v3 ~1.0Amazon S3: league/flysystem-aws-s3-v3 ~1.0
  • Rackspace: league/flysystem-rackspace ~1.0Rackspace: league/flysystem-rackspace ~1.0

S3ドライバ設定S3 Driver Configuration

S3ドライバの設定情報は、config/filesystems.php設定ファイルにあります。このファイルはS3ドライバの設定配列のサンプルを含んでいます。この配列を自由に、自分のS3設定と認証情報に合わせて、変更してください。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.

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,
],

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',
],

ディスクインスタンス取得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 applications 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');

ファイルURLFile URLs

locals3ドライバを使用するとき、指定したファイルのURLを取得するために、urlメソッドを使ってください。localドライバを使用している場合、このメソッドは通常、指定したパスの先頭に/strorageを付け、そのファイルへの相対パスを返します。s3ドライバを使用している場合、完全なリモートURLを返します。When using the local or s3 drivers, 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 driver, the fully qualified remote URL will be returned:

use Illuminate\Support\Facades\Storage;

$url = Storage::url('file1.jpg');

Note: note localドライバを使用する場合、一般公開するファイルはすべて、storage/app/publicディレクトリへ設置する必要があることを忘れないでください。さらに、storage/app/publicディレクトリへシンボリックリンクを張る必要もあります。{note} Remember, if you are using the local driver, all files that should be publicly accessible should be placed in the storage/app/public directory. Furthermore, you should create a symbolic link[#the-public-disk] to the storage/app/public directory.

ファイルメタ情報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('file1.jpg');

lastModifiedメソッドは最後にファイルが更新された時のUnixタイムスタンプを返します。The lastModified method returns the UNIX timestamp of the last time the file was modified:

$time = Storage::lastModified('file1.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に管理させたい場合は、putFileputFileAsメソッドを使います。このメソッドは、Illuminate\Http\FileIlluminate\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 desire location:

use Illuminate\Http\File;

// 自動的にファイル名としてMD5ハッシュ値が計算される
Storage::putFile('photos', new File('/path/to/photo'));

// ファイル名を指定する
Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

putFileメソッドにはいくつか重要な注意点があります。ファイル名ではなく、ディレクトリ名を指定することに注意してください。デフォルトでputFileメソッドは自動的に、ファイルの内容を元にファイル名を生成します。ファイル内容のMD5ハッシュを利用します。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 automatically generate a filename based on the contents of the file. This is accomplished by taking a MD5 hash of the file's contents. 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.

putFileputFileAsメソッドはさらに、保存ファイルの「視認性」を指定する引数も受け付けます。これは特に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 publicly accessible:

Storage::putFile('photos', new File('/path/to/photo'), 'public');

ファイルの先頭/末尾への追加Prepending & Appending To Files

prependappendメソッドで、ファイルの初めと終わりに内容を追加できます。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/file1.jpg', 'new/file1.jpg');

Storage::move('old/file1.jpg', 'new/file1.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. Simply 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メソッドは、ファイルの内容を元にファイル名を生成します。ファイル内容から生成するMD5ハッシュを利用します。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 automatically generate a filename based on the contents of the file. This is accomplished by taking a MD5 hash of the file's contents. 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.

上の例と同じ操作を行うため、Strorageファサードの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'));

Note: note とても大きなアップロードファイルを受け取った場合、ファイル名を指定したほうが良いでしょう。極端に大きなファイルでMD5ハッシュを計算すると、たくさんのメモリが消費されます。{note} If you are receiving very large file uploads, you may wish to manually specify the file name as shown below. Calculating an MD5 hash for extremely large files can be memory intensive.

ファイル名の指定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メソッドも使用できます。Of course, 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
);

ディスクの指定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統合では、複数のプラットフォームにおけるファイルパーミッションを「視認性」として抽象化しています。ファイルはpublicprivateのどちらかとして宣言します。ファイルを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');

もし、ファイルが既に保存済みであるなら、getVisibilitysetVisibilityにより、視認性を取得/設定できます。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(['file1.jpg', 'file2.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 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.

たとえばDropboxFilesystemServiceProviderのような、作成するカスタムファイルシステムのためにサービスプロバイダを用意してください。プロバイダのbootメソッドの中でStorageファサードのextendメソッドを使い、カスタムドライバを定義できます。In order to set up the custom filesystem you will need to 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 Dropbox\Client as DropboxClient;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Dropbox\DropboxAdapter;

class DropboxServiceProvider extends ServiceProvider
{
    /**
     * サービスの初期処理登録後に実行
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('dropbox', function($app, $config) {
            $client = new DropboxClient(
                $config['accessToken'], $config['clientIdentifier']
            );

            return new Filesystem(new DropboxAdapter($client));
        });
    }

    /**
     * コンテナで結合の登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

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/filesystem.php設定ファイルでdropboxドライバを使用できます。Once you have created the service provider to register the extension, you may use the dropbox driver in your config/filesystem.php configuration file.

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作