Laravel には Flysystem PHP パッケージを統合したファイルシステムが提供されている。ローカルのファイルシステムと S3 を操作できるドライバがデフォルトで提供されているのみなので、カスタムドライバを作成して Laravel のファイルシステムを拡張してみる。
extend メソッドの使用
ファイルシステムを拡張するためには Storage ファサードの extend メソッドを使用する必要があり extend メソッドにはドライバ名とLeague\Flysystem\Filesystem
を返すクロージャを指定する必要がある。League\Flysystem\Filesystemは League\Flysystem\AdapterInterface
を引数にとるので、ファイルシステムを拡張するには League\Flysystem\AdapterInterface
を実装したクラスを作成する必要がある。
// League\Flysystem\Filesystem の実装の一部
namespace League\Flysystem;
...
class Filesystem implements FilesystemInterface
{
...
public function __construct(AdapterInterface $adapter, $config = null)
{
$this->adapter = $adapter;
$this->setConfig($config);
}
...
}
AdapterInterfaceを実装する
League\Flysystem\Filesystem
のコンストラクタに渡すために League\Flysystem\AdapterInterface
を実装したクラスを作成する。実装する必要がある API の一覧はhttps://flysystem.thephpleague.com/docs/usage/filesystem-api/に記載されているので、引数の型まで合わせて実装してあげる。今回は AdapterInterface を継承した抽象クラスである League\Flysystem\Adapter\AbstractAdapter
を継承した具象クラスを作成する。
// AdapterInterface を実装する
use League\Flysystem\Adapter\AbstractAdapter;
class SampleStorageAdapter extends AbstractAdapter
{
public function write($path, $contents, $config)
{
// 実装する
}
public function writeStream($path, $resource, $config)
{
// 実装する
}
...
}
カスタムドライバを登録する
Flysystem アダプタを実装したクラスを用意したらサービスプロバイダの boot メソッド内で Storage ファサードの extend メソッドを使ってカスタムドライバを登録する。
namespace App\Providers;
...
class SampleServiceProvider extends ServiceProvider
{
...
public function boot()
{
Storage::extend('sample', function ($app, $config) {
$sample = new SampleStorageAdapter($config);
return new Filesystem($sample, $config);
});
}
}
作成したカスタムドライバを使用するためには、まずfilesystem.php
にディスク情報を登録する。
...
'sample-disk' => [
'driver' => 'sample',
],
config/filesystem.php
にディスク情報を登録したら Storage ファサードの disk メソッドを使用して disk 名を指定することでディスクインスタンスにアクセスすることができる。
Storage::disk('sample-disk')->read('path/to/get/content')