Readouble

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

イントロダクション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 is 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.

PublicディスクThe Public Disk

publicディスクは一般公開へのアクセスを許すファイルを意味しています。デフォルトのpublicディスクは、localドライバを使用しており、storage/app/public下に存在しているファイルです。Webからのアクセスを許すには、public/storageからstorage/app/publicへシンボリックリンクを張る必要があります。この手法により、公開ファイルを一つのディレクトリへ留め、Envoyerのようなリリース時のダウンタイムが起きない開発システムを使っている場合、各リリース間でファイルを簡単に共有できます。The public disk is meant 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].

もちろん、ファイルを保存し、シンボリックリンクが張られたら、assetヘルパを使いファイルへのURLを生成できます。Of course, once a file has been stored and the symbolic link has been created, you can create an 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, note that 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');

他のドライバ使用要件Other Driver Prerequisites

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

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

基本的な使用法Basic Usage

ディスクインスタンス取得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:

<?php

namespace App\Http\Controllers;

use Storage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定したユーザのアバターを更新
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function updateAvatar(Request $request, $id)
    {
        $user = User::findOrFail($id);

        Storage::put(
            'avatars/'.$user->id,
            file_get_contents($request->file('avatar')->getRealPath())
        );
    }
}

複数ディスクを使用する場合、Storageファサードに対しdiskメソッドを使用し特定のディスクへアクセスできます。もちろんdiskに続けメソッドをチェーンして実行できます。When using multiple disks, you may access a particular disk using the disk method on the Storage facade. Of course, you may continue to chain methods to execute methods on the disk:

$disk = Storage::disk('s3');

$contents = Storage::disk('local')->get('file.jpg');

ファイル取得Retrieving Files

getメソッドは指定したファイルの内容を取得するために使用します。メソッドはファイルの内容をそのまま返します。The get method may be used to retrieve the contents of a given file. The raw string contents of the file will be returned by the method:

$contents = Storage::get('file.jpg');

existsメソッドは指定したディスクにファイルが存在しているかを判定するために使用します。The exists method may be used to determine if a given 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.

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

注意: localドライバ使用時、storage/app/publicディレクトリへ、public/storageからのリンクを張るのを忘れないでください。Note: When using the local driver, be sure to create a symbolic link at public/storage[#the-public-disk] which points to the storage/app/public directory.

ファイルのメタ情報File Meta Information

sizeメソッドはファイルのサイズをバイトで取得するために使います。The size method may be used to get the size of the file in bytes:

$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 a file on 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:

Storage::put('file.jpg', $contents);

Storage::put('file.jpg', $resource);

copyメソッドは存在しているファイルをディスクの新しい場所へコピーします。The copy method may be used to copy an existing file to a new location on the disk:

Storage::copy('old/file1.jpg', 'new/file1.jpg');

moveメソッドは存在しているファイルをリネームするか、新しい場所へ移動します。The move method may be used to rename or move an existing file to a new location:

Storage::move('old/file1.jpg', 'new/file1.jpg');

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

prependappendメソッドで、ファイルの初めと終わりに内容を簡単に挿入できます。The prepend and append methods allow you to easily insert content at the beginning or end of a file:

Storage::prepend('file.log', 'Prepended Text');

Storage::append('file.log', 'Appended Text');

ファイル視認性File Visibility

ファイル視認性はgetVisibilitysetVisibilityメソッドにより取り扱います。視認性とはマルチプラットフォーム間におけるファイルパーミッションを抽象したものです。File visibility can be retrieved and set via the getVisibility and setVisibility methods. Visibility is the abstraction of file permissions across multiple platforms:

Storage::getVisibility('file.jpg');

Storage::setVisibility('file.jpg', 'public');

さらに、putメソッドによりファイルを設定するとき、視認性を指定することもできます。視認性はpublicprivateです。Additionally, you can set the visibility when setting the file via the put method. The valid visibility values are public and private:

Storage::put('file.jpg', $contents, 'public');

ファイル削除Deleting Files

deleteメソッドはディスクから削除するファイルを単独、もしくは配列で受け付けます。The delete method accepts a single filename or an array of files to remove from the disk:

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:

$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, including all of its files, from the disk:

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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作