LoginSignup
0
0

More than 1 year has passed since last update.

【覚書】Laravelでファサードを作る方法

Last updated at Posted at 2021-06-25

毎度忘れては調べて作っている上に、なかなか正解に辿り着けないので覚書です。

手順

準備

適当にクラス作ります

app/Http/Controllers/hoge.php
class hoge
{
    public function byTen($num)
    {
        return $num * 10;
    }
}

ファサードの派生クラス作成

app/Facades/hoge.php
<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class hoge extends Facade
{
    protected static function getFacadeAccessor(){
        return 'hoge';
    }
}

サービスプロバイダ作成

app/Providers/hogeServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class hogeServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
      //
      $this->app->bind(
        'hoge',
          'App\Http\Controllers\hoge'
      );
    }
}

Configに登録

config/app.php

'providers' => [
    App\Providers\hogeServiceProvider::class,
]

'aliases' => [
    'hoge' => App\Facades\hoge::class,
]

キャッシュクリア

console
php artisan optimize:clear
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0