laravel门面实例

ps:此文根据上文的基础改制而来

1、定义服务类

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


namespace App\Facades;

class Test
{
    public function doSomething()
    {
        echo 'This is TestClass\'s method doSomething';
    }
}
 

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

<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

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

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

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Facades\Test;

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

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('test',function(){
            return new Test;
        });

    }
}

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

'aliases' => [

    ...//其他门面类别名映射

    'TestClass' => App\Facades\TestClass::class,
],

最后修改TestController代码如下:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller; use TestClass;
class TestController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { TestClass::doSomething(); } }

 

posted on 2017-10-17 18:51  running-fly  阅读(512)  评论(0)    收藏  举报

导航