2016-09-22 143 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