Laravel Facade(ファサード)とは
ファサード作成
1 ファサードに登録したい処理(クラス)を作成
ディレクトリーはどこに作成するといったルールもなく、特に指定なし。
<?php
namespace App\Reffects;
class MyName
{
public function run()
{
return 'Myname is yuki fujimoto';
}
}
2 サービスプロバイダーに登録
App\Providers\AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//ここ↓
$this->app->bind('MyName', \App\Reffects\MyName::class);
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
3 ファサード作成
Illuminate\Support\Facades
ファサードを作成するコマンドはなく、自分で手動で作成して下さい。
ファサードではサービスプロバイダーに登録した名前で呼び出す=処理クラスを呼び出すだけ
<?php
namespace Illuminate\Support\Facades;
class Own extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'MyName';
}
}
4 呼び出す
どこの階層でも自由に呼び出し使用することができます。
ただし、必ずuse で呼び出して下さい。
use Illuminate\Support\Facades\Own;
Route::get('/', function () {
dd(Own::run());
return view('owner.welcome');
});
これで自由に自作ファサードを呼び出し、作成することができるようになりました。
さらにuse文をなくす方法をご紹介します。
/config/app.phpのaliases配列に自作ファサードの設定を追記します。
'aliases' => Facade::defaultAliases()->merge([
//ここ↓
'Own' => Illuminate\Support\Facades\Own::class, //これを追加
])->toArray(),
これでuse文が必要なく、呼び出すことができるようになりました。