【问题标题】:laravel create service providerlaravel 创建服务提供者
【发布时间】:2016-09-23 02:27:04
【问题描述】:

我创建了一个服务提供者并在 app.php 中添加了提供者,但是我该如何使用它呢?

<?php

namespace App\Providers;    
use Illuminate\Support\ServiceProvider;    
use App\Helpers\api\gg\gg;

class ApiServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function boot()
    {
    }
    public function register()
    {
        $this->app->bind(gg::class, function ()
        {
            return new gg;
        });
    }
    public function provides()
    {
        return [gg::class];
    }
}

gg 类在 App\Helpers\api\gg 文件夹中,我想在任何地方都使用这个类

gg::isReady();

app.php

'providers' => [
        ...
        App\Providers\ApiServiceProvider::class,
        ...

    ]

homecontroller@index

public function index()
{
    //how can use this provider in there ?
    return view('pages.home');
}

【问题讨论】:

    标签: php laravel laravel-5 service-provider


    【解决方案1】:

    当您执行$this-&gt;app-&gt;bind() 时,您已将一个类的实例绑定到IoC。当您绑定到 IoC 时,您可以在整个应用程序中使用它。但是:

    您的命名空间违反了PSR-1 合规性。这是因为您没有使用StudlyCaps

    不好use App\Helpers\api\gg\gg

    use App\Helpers\Api\GG\GG

    相应地重命名您的文件夹/文件。排序后,您的绑定函数实际上应该更改为singleton。这是因为你想要一个持久的状态,而不是一个可重用的模型。

    $this->app->singleton(GG::class, function(){
        return new GG;
    });
    

    您也不应该在每个函数中检查-&gt;isReady(),这是anti-pattern 的一个示例。相反,这应该在中间件中:

    php artisan make:middleware VerifyGGReady
    

    将此添加到您的内核:

    protected $routeMiddleware = [
        //other definitions
    
        'gg_ready' => App\Http\Middleware\VerifyGGReady::class
    ];
    

    更新中间件中的handle() 函数:

    public function handle($request, Closure $next) {
        if ($this->app->GG->isReady()) {
            return $next($request);
        }
    
        return redirect('/'); //gg is not ready
    });
    

    然后在你的路由组中初始化它:

    Route::group(['middleware' => ['gg_ready']], function(){
        //requires GG to be ready
    });
    

    或直接在路线上:

    Route::get('acme', 'AcmeController@factory')->middleware('gg_ready');
    

    或者在你的控制器中使用它:

    $this->middleware('gg_ready');
    

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2015-10-24
      • 2016-10-06
      • 1970-01-01
      相关资源
      最近更新 更多