2016-09-22 8 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クラスは、App \ヘルパー\ 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にバインドすると、アプリケーション全体で利用できるようになります。 HOWEVER:

あなたのネームスペースは、PSR-1に準拠しています。これは、StudlyCapsを使用していないためです。 BAD

use App\Helpers\api\gg\gg

GOODuse App\Helpers\Api\GG\GG

フォルダ/ファイルの名前を適宜変更してください。ソートされると、バインド関数は実際にsingletonに変更されます。これは、再利用可能なモデルではなく、永続状態を必要とするためです。

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

また、それはanti-patternの一例ですが、すべての機能に->isReady()をチェックするべきではありません。

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

関連する問題