0

i make a serviceprovider and add provider in app.php but how can i use it ?

<?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 class is in App\Helpers\api\gg folder and i want use this class everywhere like that

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');
}
Hanik
  • 317
  • 2
  • 6
  • 25

1 Answers1

1

When you did $this->app->bind(), you've bound an instance of a class to the IoC. When you bind to the IoC you make that available throughout the entirety of the application. HOWEVER:

Your namespaces break PSR-1 compliance. This is because you are not using StudlyCaps.

BAD: use App\Helpers\api\gg\gg

GOOD: use App\Helpers\Api\GG\GG.

Rename your folders/files accordingly. With that sorted, your bind function should actually change to a singleton. This is because you want a persistent state, not a reusable model.

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

You also should not check ->isReady() in every function, that's an example of an anti-pattern. Instead, this should be in a middleware:

php artisan make:middleware VerifyGGReady

Add this to your Kernel:

protected $routeMiddleware = [
    //other definitions

    'gg_ready' => App\Http\Middleware\VerifyGGReady::class
];

Update the handle() function in your middleware:

public function handle($request, Closure $next) {
    if ($this->app->GG->isReady()) {
        return $next($request);
    }

    return redirect('/'); //gg is not ready
});

And then either initialize it in your route groups:

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

Or directly on a route:

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

Or use it in your controller:

$this->middleware('gg_ready');
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110