2016-09-22 184 views
0

我做了一個serviceprovider,並在app.php中添加提供程序,但我該如何使用它?laravel創建服務提供商

<?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類是在應用程序\助手\ API \ GG文件夾,我想在任何地方使用這個類像

gg::isReady(); 

app.php

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

    ] 

的HomeController @指數

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

回答

0

當你做了$this->app->bind(),您已將類的實例綁定到IoC。當您綁定到IoC時,您可以在整個應用程序中使用它。但:

您的命名空間符合PSR-1。這是因爲您沒有使用StudlyCaps

BADuse App\Helpers\api\gg\gg

GOODuse App\Helpers\Api\GG\GG

相應地重新命名文件夾/文件。在排序後,你的綁定函數實際上應該改爲singleton。這是因爲你想要一個持久化狀態,而不是一個可重用的模型。

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

你也應該不會在每一個功能檢查->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', '[email protected]')->middleware('gg_ready'); 

或者在你的控制器使用方法:

$this->middleware('gg_ready'); 
+0

我會嘗試。謝謝 – Hanik