イントロダクションIntroduction
ファサードはアプリケーションのサービスコンテナに用意したクラスに「静的」なインターフェイスを提供しています。Laravelは多くのファサードを使用していますが、多分皆さんは気が付かないまま使用していることでしょう! Laravelの「ファサード(facade)」は、サービスコンテナ下で動作しているクラスに対し、"static proxy"として動作しています。これにより伝統的な静的メソッドよりも簡潔で、テストの行いやすさと柔軟性を保ちながらも、記述的な書き方が行えます。Facades provide a "static" interface to classes that are available in the application's service container[/docs/{{version}}/container]. Laravel ships with many facades, and you have probably been using them without even knowing it! Laravel "facades" serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.
自分のアプリケーションやパッケージでも、ファサードを作成したい場合があるでしょう。そのため、コンセプトと開発方法、クラスの使い方を説明していきます。Occasionally, you may wish to create your own facades for your application's and packages, so let's explore the concept, development and usage of these classes.
注目: ファサードを学び始める前に、Laravelのサービスコンテナに慣れておくことを強くおすすめします。Note: Before digging into facades, it is strongly recommended that you become very familiar with the Laravel service container[/docs/{{version}}/container].
解説Explanation
Laravelアプリケーションに関する文脈で「ファサード」は、コンテナを通じてオブジェクトにアクセス方法を提供するクラスのことを意味します。Facadeクラス中のメカニズムでこれを行なっています。Laravelのファサードと、皆さんが作成するカスタムファサードは、Facadeクラスを拡張します。In the context of a Laravel application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the Facade class. Laravel's facades, and any custom facades you create, will extend the base Facade class.
ファサードクラスで実装する必要があるのはgetFacadeAccessorだけです。getFacadeAccessorメソッドの役目はコンテナを通じたインスタンスの依存解決に何を使用するかを定義することです。Facade基本クラスは__callStatic()マジックメソッドを使用し、あなたのファサードからの呼び出しを依存解決してインスタンス化したオブジェクトへと届けます。Your facade class only needs to implement a single method: getFacadeAccessor. It's the getFacadeAccessor method's job to define what to resolve from the container. The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to the resolved object.
Cache::getのようにファサードの呼び出しが行われると、LaravelはサービスコンテナでCacheマネージャーを依存解決し、そのクラスのgetメソッドを呼び出します。技術的な言い方をすれば、Laravelのファサードは、サービスローケーターとしてのLaravelのサービスコンテナを使用した、使いやすい記法のことです。So, when you make a facade call like Cache::get, Laravel resolves the Cache manager class out of the service container and calls the get method on the class. In technical terms, Laravel Facades are a convenient syntax for using the Laravel service container as a service locator.
実際の使用Practical Usage
下の例では、Laravelのキャッシュシステムを呼び出しています。これを読むと、一見Cacheクラスのstaticなgetメソッドが呼び出されていのだと考えてしまうことでしょう。In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static method get is being called on the Cache class.
$value = Cache::get('key');
ところが、Illuminate\Support\Facades\Cacheクラスを見てもらえば、staticのgetメソッドは存在していないことが分かります。However, if we look at that Illuminate\Support\Facades\Cache class, you'll see that there is no static method get:
class Cache extends Facade {
/**
* コンポーネントの登録名を取得する
*
* @return string
*/
protected static function getFacadeAccessor() { return 'cache'; }
}
CacheファサードはベースのFacadeクラスを拡張し、getFacadeAccessor()メソッドを定義しています。思い出してください。このメソッドの仕事はサービスコンテナで結合した名前を返すことでした。The Cache class extends the base Facade class and defines a method getFacadeAccessor(). Remember, this method's job is to return the name of a service container binding.
ユーザーがCacheファサードのどのstaticメソッドを利用しようと、Laravelはサービスコンテナからcacheに結び付けられたインスタンスを依存解決し、要求されたメソッドを(この場合はget)そのオブジェクトに対し実行します。When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.
ですから、Cache::getの呼び出しは以下のように書き直すこともできます。So, our Cache::get call could be re-written like so:
$value = $app->make('cache')->get('key');
ファサードのインポートImporting Facades
コントローラーが名前空間下にあるときにファサードを利用するには、その名前空間へファサードクラスをインポートする必要があることを覚えておいてください。全てのファサードはグローバル名前空間にあります。Remember, if you are using a facade in a controller that is namespaced, you will need to import the facade class into the namespace. All facades live in the global namespace:
<?php namespace App\Http\Controllers;
use Cache;
class PhotosController extends Controller {
/**
* 写真を全て取得する
*
* @return Response
*/
public function index()
{
$photos = Cache::get('photos');
//
}
}
ファサードの作成Creating Facades
ファサードを作成するとアプリケーションやパッケージをシンプルにすることができます。必要なのは3つだけです。Creating a facade for your own application or package is simple. You only need 3 things:
- サービスコンテナへの結合A service container binding.
- ファサードクラスA facade class.
- ファサードエイリアスの設定A facade alias configuration.
例を見てください。PaymentGateway\Paymentクラスを定義しています。Let's look at an example. Here, we have a class defined as PaymentGateway\Payment.
namespace PaymentGateway;
class Payment {
public function process()
{
//
}
}
このクラスをサービスコンテナで依存解決できるようにする必要があります。そのため、サービスプロバイダーに結合を追加しましょう。We need to be able to resolve this class from the service container. So, let's add a binding to a service provider:
App::bind('payment', function()
{
return new \PaymentGateway\Payment;
});
この結合を設置する良い方法は、PaymentServiceProviderという名前の新しいサービスプロバイダーを作成し、registerメソッドへ追加することでしょう。次にconfig/app.php設定ファイルで、このサービスプロバイダーがロードされるように指定しましょう。A great place to register this binding would be to create a new service provider[/docs/{{version}}/container#service-providers] named PaymentServiceProvider, and add this binding to the register method. You can then configure Laravel to load your service provider from the config/app.php configuration file.
次に、ファサードクラスを作成しましょう。Next, we can create our own facade class:
use Illuminate\Support\Facades\Facade;
class Payment extends Facade {
protected static function getFacadeAccessor() { return 'payment'; }
}
最後にお望みであれば、config/app.php設定ファイルのaliases配列に、このファサードのエイリアスを付け加えることもできます。これで、Paymentクラスインスタンスのprocessメソッドを呼び出すことができるようになりました。Finally, if we wish, we can add an alias for our facade to the aliases array in the config/app.php configuration file. Now, we can call the process method on an instance of the Payment class.
Payment::process();
オートローディングエイリアスの注意点A Note On Auto-Loading Aliases
PHPが未定義のタイプヒントをオートロードしないため、aliases配列にインスタンスが指定できない場合があります。もし、\ServiceWrapper\ApiTimeoutExceptionをApiTimeoutExceptionというエイリアス名で定義し、\ServiceWrapper外の名前空間でcatch(ApiTimeoutException $e)しても、投げられたその例外は捕捉されません。似たような問題は、エイリアスされたクラスへのタイプヒントを持つモデルでも、見かけられます。唯一の依存解決法は、そのようなエイリアスの参照に先立ち、それぞれのファイルの先頭で、必要なタイプヒントをuseで指定しておく方法しかありません。Classes in the aliases array are not available in some instances because PHP will not attempt to autoload undefined type-hinted classes[https://bugs.php.net/bug.php?id=39003]. If \ServiceWrapper\ApiTimeoutException is aliased to ApiTimeoutException, a catch(ApiTimeoutException $e) outside of the namespace \ServiceWrapper will never catch the exception, even if one is thrown. A similar problem is found in classes which have type hints to aliased classes. The only workaround is to forego aliasing and use the classes you wish to type hint at the top of each file which requires them.
ファサードのモックMocking Facades
ファサードがどうしてこのような仕組みを持っているのか、その理由の重要な一面がユニットテストです。実際、ファサードが存在している一番大きな理由がテストの行いやすさです。詳細はドキュメントのファサードのモックをご覧ください。Unit testing is an important aspect of why facades work the way that they do. In fact, testability is the primary reason for facades to even exist. For more information, check out the mocking facades[/docs/{{version}}/testing#mocking-facades] section of the documentation.
ファサードクラス一覧Facade Class Reference
以下は全ファサードと、実際のクラスの一覧です。これは特定のファサードを元にし、APIドキュメントを素早く探したい場合に便利な道具になります。対応するサービスコンテナ結合キーも記載しています。Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The service container binding[/docs/{{version}}/container] key is also included where applicable.
| ファサードFacade | クラスClass | サービスコンテナ結合Service Container Binding |
|---|---|---|
| AppApp | Illuminate\Foundation\ApplicationIlluminate\Foundation\Application[http://laravel.com/api/{{version}}/Illuminate/Foundation/Application.html] | appapp |
| ArtisanArtisan | Illuminate\Console\ApplicationIlluminate\Console\Application[http://laravel.com/api/{{version}}/Illuminate/Console/Application.html] | artisanartisan |
| AuthAuth | Illuminate\Auth\AuthManagerIlluminate\Auth\AuthManager[http://laravel.com/api/{{version}}/Illuminate/Auth/AuthManager.html] | authauth |
| Auth (インスタンス)Auth (Instance) | Illuminate\Auth\GuardIlluminate\Auth\Guard[http://laravel.com/api/{{version}}/Illuminate/Auth/Guard.html] | |
| BladeBlade | Illuminate\View\Compilers\BladeCompilerIlluminate\View\Compilers\BladeCompiler[http://laravel.com/api/{{version}}/Illuminate/View/Compilers/BladeCompiler.html] | blade.compilerblade.compiler |
| BusBus | Illuminate\Contracts\Bus\DispatcherIlluminate\Contracts\Bus\Dispatcher[http://laravel.com/api/{{version}}/Illuminate/Contracts/Bus/Dispatcher.html] | |
| CacheCache | Illuminate\Cache\CacheManagerIlluminate\Cache\CacheManager[http://laravel.com/api/{{version}}/Illuminate/Cache/Repository.html] | cachecache |
| ConfigConfig | Illuminate\Config\RepositoryIlluminate\Config\Repository[http://laravel.com/api/{{version}}/Illuminate/Config/Repository.html] | configconfig |
| CookieCookie | Illuminate\Cookie\CookieJarIlluminate\Cookie\CookieJar[http://laravel.com/api/{{version}}/Illuminate/Cookie/CookieJar.html] | cookiecookie |
| CryptCrypt | Illuminate\Encryption\EncrypterIlluminate\Encryption\Encrypter[http://laravel.com/api/{{version}}/Illuminate/Encryption/Encrypter.html] | encrypterencrypter |
| DBDB | Illuminate\Database\DatabaseManagerIlluminate\Database\DatabaseManager[http://laravel.com/api/{{version}}/Illuminate/Database/DatabaseManager.html] | dbdb |
| DB (インスタンス)DB (Instance) | Illuminate\Database\ConnectionIlluminate\Database\Connection[http://laravel.com/api/{{version}}/Illuminate/Database/Connection.html] | |
| EventEvent | Illuminate\Events\DispatcherIlluminate\Events\Dispatcher[http://laravel.com/api/{{version}}/Illuminate/Events/Dispatcher.html] | eventsevents |
| FileFile | Illuminate\Filesystem\FilesystemIlluminate\Filesystem\Filesystem[http://laravel.com/api/{{version}}/Illuminate/Filesystem/Filesystem.html] | filesfiles |
| HashHash | Illuminate\Contracts\Hashing\HasherIlluminate\Contracts\Hashing\Hasher[http://laravel.com/api/{{version}}/Illuminate/Contracts/Hashing/Hasher.html] | hashhash |
| InputInput | Illuminate\Http\RequestIlluminate\Http\Request[http://laravel.com/api/{{version}}/Illuminate/Http/Request.html] | requestrequest |
| LangLang | Illuminate\Translation\TranslatorIlluminate\Translation\Translator[http://laravel.com/api/{{version}}/Illuminate/Translation/Translator.html] | translatortranslator |
| LogLog | Illuminate\Log\WriterIlluminate\Log\Writer[http://laravel.com/api/{{version}}/Illuminate/Log/Writer.html] | loglog |
| MailMail | Illuminate\Mail\MailerIlluminate\Mail\Mailer[http://laravel.com/api/{{version}}/Illuminate/Mail/Mailer.html] | mailermailer |
| PasswordPassword | Illuminate\Auth\Passwords\PasswordBrokerIlluminate\Auth\Passwords\PasswordBroker[http://laravel.com/api/{{version}}/Illuminate/Auth/Passwords/PasswordBroker.html] | auth.passwordauth.password |
| QueueQueue | Illuminate\Queue\QueueManagerIlluminate\Queue\QueueManager[http://laravel.com/api/{{version}}/Illuminate/Queue/QueueManager.html] | queuequeue |
| Queue (インスタンス)Queue (Instance) | Illuminate\Queue\QueueInterfaceIlluminate\Queue\QueueInterface[http://laravel.com/api/{{version}}/Illuminate/Queue/QueueInterface.html] | |
| Queue (ベースクラス)Queue (Base Class) | Illuminate\Queue\QueueIlluminate\Queue\Queue[http://laravel.com/api/{{version}}/Illuminate/Queue/Queue.html] | |
| RedirectRedirect | Illuminate\Routing\RedirectorIlluminate\Routing\Redirector[http://laravel.com/api/{{version}}/Illuminate/Routing/Redirector.html] | redirectredirect |
| RedisRedis | Illuminate\Redis\DatabaseIlluminate\Redis\Database[http://laravel.com/api/{{version}}/Illuminate/Redis/Database.html] | redisredis |
| RequestRequest | Illuminate\Http\RequestIlluminate\Http\Request[http://laravel.com/api/{{version}}/Illuminate/Http/Request.html] | requestrequest |
| ResponseResponse | Illuminate\Contracts\Routing\ResponseFactoryIlluminate\Contracts\Routing\ResponseFactory[http://laravel.com/api/{{version}}/Illuminate/Contracts/Routing/ResponseFactory.html] | |
| RouteRoute | Illuminate\Routing\RouterIlluminate\Routing\Router[http://laravel.com/api/{{version}}/Illuminate/Routing/Router.html] | routerrouter |
| SchemaSchema | Illuminate\Database\Schema\BlueprintIlluminate\Database\Schema\Blueprint[http://laravel.com/api/{{version}}/Illuminate/Database/Schema/Blueprint.html] | |
| SessionSession | Illuminate\Session\SessionManagerIlluminate\Session\SessionManager[http://laravel.com/api/{{version}}/Illuminate/Session/SessionManager.html] | sessionsession |
| Session (インスタンス)Session (Instance) | Illuminate\Session\StoreIlluminate\Session\Store[http://laravel.com/api/{{version}}/Illuminate/Session/Store.html] | |
| StorageStorage | Illuminate\Contracts\Filesystem\FactoryIlluminate\Contracts\Filesystem\Factory[http://laravel.com/api/{{version}}/Illuminate/Contracts/Filesystem/Factory.html] | filesystemfilesystem |
| URLURL | Illuminate\Routing\UrlGeneratorIlluminate\Routing\UrlGenerator[http://laravel.com/api/{{version}}/Illuminate/Routing/UrlGenerator.html] | urlurl |
| ValidatorValidator | Illuminate\Validation\FactoryIlluminate\Validation\Factory[http://laravel.com/api/{{version}}/Illuminate/Validation/Factory.html] | validatorvalidator |
| Validator (インスタンス)Validator (Instance) | Illuminate\Validation\ValidatorIlluminate\Validation\Validator[http://laravel.com/api/{{version}}/Illuminate/Validation/Validator.html] | |
| ViewView | Illuminate\View\FactoryIlluminate\View\Factory[http://laravel.com/api/{{version}}/Illuminate/View/Factory.html] | viewview |
| View (インスタンス)View (Instance) | Illuminate\View\ViewIlluminate\View\View[http://laravel.com/api/{{version}}/Illuminate/View/View.html] |