Laravel 门面实例教程 —— 创建自定义 Facades 类


使用Laravel框架必不可少的会用到它很多强大的门面类(Facades),门面提供了一个“静态”接口到服务容器中绑定的类,官方文档阐述了如何使用系统自带的缓存门面,我们这里演示如何创建并使用一个自定义的门面类。

注:本教程基于上一节服务提供者做部分代码修改,不熟悉的请参阅。

我们首先创建一个需要绑定到服务容器的Test类:

  1. <?php
  2.  
  3. namespace App\Facades;
  4.  
  5. class Test
  6. {
  7. public function doSomething()
  8. {
  9. echo 'This is TestClass\'s method doSomething';
  10. }
  11. }

然后创建一个静态指向Test类的门面类TestClass:

  1. <?php
  2.  
  3. namespace App\Facades;
  4.  
  5. use Illuminate\Support\Facades\Facade;
  6.  
  7. class TestClass extends Facade
  8. {
  9. protected static function getFacadeAccessor()
  10. {
  11. return 'test';
  12. }
  13. }

接下来我们要在服务提供者中绑定Test类到服务容器,修改TestServiceProvider类如下:

  1. <?php
  2.  
  3. namespace App\Providers;
  4.  
  5. use Illuminate\Support\ServiceProvider;
  6. use App\Services\TestService;
  7. use App\Facades\Test;
  8.  
  9. class TestServiceProvider extends ServiceProvider
  10. {
  11. /**
  12. * Bootstrap the application services.
  13. *
  14. * @return void
  15. */
  16. public function boot()
  17. {
  18.  
  19. }
  20.  
  21. /**
  22. * Register the application services.
  23. *
  24. * @return void
  25. */
  26. public function register()
  27. {
  28. $this->app->singleton('test',function(){
  29. //return new TestService();
  30. return new Test;
  31. });
  32.  
  33. $this->app->bind('App\Contracts\TestContract',function(){
  34. return new TestService();
  35. });
  36. }
  37. }

再然后需要到配置文件config/app.php中注册门面类别名:

  1. 'aliases' => [
  2.  
  3. ...//其他门面类别名映射
  4.  
  5. 'TestClass' => App\Facades\TestClass::class,
  6. ],

最后修改TestController代码如下:

  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6.  
  7. use App\Http\Requests;
  8. use App\Http\Controllers\Controller;
  9.  
  10. use App;
  11. use TestClass;
  12. use App\Contracts\TestContract;
  13.  
  14. class TestController extends Controller
  15. {
  16.  
  17. public function __construct(TestContract $test){
  18. $this->test = $test;
  19. }
  20.  
  21. /**
  22. * Display a listing of the resource.
  23. *
  24. * @return Response
  25. */
  26. public function index()
  27. {
  28. // $test = App::make('test');
  29. // $test->callMe('TestController');
  30. //$this->test->callMe('TestController');
  31.  
  32. TestClass::doSomething();
  33. }
  34.  
  35. ...//其他方法
  36. }

注意:不要忘了在调用门面类TestClass的文件顶部使用use TestClass;引入TestClass,否则将不能正确调用。

好了,我们可以去浏览器中测试了,访问http://laravel.app:8000/test,页面将会输出:

  1. This is TestClass's method doSomething