Facade 门面自定义使用
门面自定义使用
- 在 app/Services 目录下创建 TestService
<?php
namespace App\Services;
class TestService
{
public function callMe($controller)
{
dd('Call Me From TestServiceProvider In '.$controller);
}
}
- 在 app 目录下新建 Facades 目录
- 在 app/Facades 目录下新建 Test
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static callMe(string $controller)
*
* @see \App\Services\TestService
*/
class Test extends Facade
{
protected static function getFacadeAccessor(){
return 'test';
}
}
- 创建服务提供者
php artisan make:provider TestServiceProvider
- 在 TestServiceProvider boot方法中为实例绑定别名
public function boot()
{
//使用singleton绑定单例
$this->app->singleton('test',function(){
return new TestService();
});
}
- 在app/congfig/app.php 文件中注册 服务提供者、门面别名
'providers' => [
...
\App\Providers\TestServiceProvider::class,
...
],
'aliases' => [
...
'Test' => \App\Facades\Test::class,
...
]
- 在控制器中使用
use App\Facades\Test as TestFacade;
public function index(Request $request){
TestFacade::callMe('123');
}
本作品采用《CC 协议》,转载必须注明作者和本文链接