欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

创建 Laravel Facades 门面

在laravel5中创建门面步骤
  • 创建一个类文件.
  • 将类型文件绑定到服务提供者
  • 注册服务提供者为提供者到Config\app.php文件
  • 创建类扩展到Illuminate\Support\Facades\Facade
    -注册别名到Config\app.php文件

Step 1 - 创建类文件,(例我们想将所有调用微信的接口放在门面中 )App\Api\Weixin.php

<?php

namespace App\Api;

class Weixin{
    //某个方法
    public function get()
    {
        echo "test";
    }
}

Step 2 - 将类绑定到服务提供者

执行如下命令

php artisan make:provider WeixinServiceProvider
然后将下面代码添加到服务提供者的register函数中

App::bind('weixin', function()
 {
      $this->app->bind('Weixin','App\Api\Weixin');
 });

添加完之后如下

<?php

namespace App\Providers;use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('Weixin','App\Api\Weixin');
//$this->app->singleton('Weixin','App\Api\Weixin'); //singleton 一次绑定,以后的话 只取这个唯一的实例 这一句 可能有问题 
} }

Step 3 - 注册服务提供者为提供者到Config\app.php文件
将下面代码添加到Config\app.php文件的providers数组中

 App\Providers\WeixinServiceProvider::class,

Step 4 - 添加扩展到 Illuminate\Support\Facades\Facade的类

例创建如下类 App\Api\Facades\Weixin.php

<?php

namespace App\Api\Facades;
use Illuminate\Support\Facades\Facade;

class Someclas extends Facade{
    protected static function getFacadeAccessor() { 
        return 'Weixin ';
     }
}

Step 5 - 注册别名到Config\app.php文件的aliases数组

'Weixin'    => App\Api\Facades\Weixin::class

创建路由进行测试
App\Http\routes.php

Route::get('/', function(){
    Weixin::get();
});
普通分类: