0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel環境でオリジナル関数クラスをファサードとして登録する

Posted at

1. Facadeファイル群を作ります。

【階層】
laravel/
 └app/
  └MyFacades/
   └Hoge/
    └Hoge.php
     Facades/
      └Hoge.php

app/MyFacades/Hoge/Hoge.php
namespace Hoge;
class Hoge {
    public static function fuga() {
    }
}
app/MyFacades/Hoge/Facades/Hoge.php
namespace Hoge\Facades;
class HogeFacade extends Facade {
    protected static function getFacadeAccessor() {
        return 'hoge';
    }
}

※関数は app/MyFacades/Hoge/Hoge.php のクラス内に static で書いていきます。

2. 独自 Facade 追加用のサービスプロバイダーを作ります。

$ php artisan make:provider MyFacadeServiceProvider

3. ファサードのネームスペースを登録する

public function boot() はさわらずそのまま。
public function register() に追記します。

laravel/app/providers/MyFacadeServiceProvider.php
    public function register() {
        $this->app->bind('hoge', function($app) {
                return new \Hoge\HogeFacade;
            }
        );
    }

4. laravel/composer.json の autoload->files に追加

laravel/composer.json
{
    "autoload": {
        "files": [
            "app/MyFacades/Hoge/Hoge.php"
        ]
    },
    ...

5. composer.json を適用

$ composer dump-autoload

6. laravel/config/app.php に provider とエイリアス(名前空間)を登録

config/app.php
return [
    ...
    'providers' => [
        ...
        App\Providers\MyFacadeServiceProvider::class,
        ...
    ],

    'aliases' => [
        ...
        'Func' => Hoge\Hoge::class,
        ...
    ],
    ...

7. サーバーのパーミッションを変更しておく

$ chmod 777 bootstrap/cache/services.php

以上で、\Func::fuga(); でどこからでも関数が使えるようになります!

0
1
2

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?