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

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

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

我们首先创建一个需要绑定到服务容器的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,页面将会输出:

This is TestClass's method doSomething

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值