5 分鐘構建自己得 Facade demo

wz8081633發表於2019-11-15
php artisan make:provider MyServiceProvider

開啟建立好的 MyServiceProvider.php 並修改檔案如下,最下方 附加class B 是方便測試使用

 
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class TestProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function register()
    {
        $this->app->singleton('my-facade',function(){
            return new B();
        });
    }

    /**
     * Bootstrap services.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function boot()
    {
        //
    }
}

class B{
    public function b(){
        echo 'this class  B  function a ,you are right~!';
    }
}

在app.php 中 分別加入

'providers'=>[
        ......
        App\Providers\MyServiceProvider::class,
]
'aliases' => [
        ......
        'MyFacade'=>\App\Providers\Facades\MyProvider::class,
]

在app/Providers資料夾下建立Facades資料夾 並建立 MyFacade.php檔案

namespace App\Providers\Facades;
use Illuminate\Support\Facades\Facade;

class MyFacade extends Facade
{
    public static function getFacadeAccessor()
    {
        return 'my-facade';
    }
}

至此,大功告成
為了方便測試,直接建立command 進行test
執行 php artisan make:command Misc 並修改生成的檔案如下

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Misc extends Command\
{
    protected $signature = 'misc';

    protected $description = 'test my facade';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        \MyFacade::b();
    }
}

php artisan misc

This yourself Facade class B function b ,you are right~!

相關文章