首页 > 其他 > 详细

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

时间:2019-03-15 15:45:39      阅读:194      评论:0      收藏:0      [点我收藏+]

 

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

<?php

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\Services\TestService;
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 TestService();
            return new Test;
        });

        $this->app->bind(‘App\Contracts\TestContract‘,function(){
            return new TestService();
        });
    }
}

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

‘aliases‘ => [

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

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

最后修改TestController代码如下:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App;
use TestClass;
use App\Contracts\TestContract;

class TestController extends Controller
{

    public function __construct(TestContract $test){
        $this->test = $test;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        // $test = App::make(‘test‘);
        // $test->callMe(‘TestController‘);
        //$this->test->callMe(‘TestController‘);

       TestClass::doSomething();
    }

    ...//其他方法
}

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

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

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

原文:https://www.cnblogs.com/php-linux/p/10537320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!