Confused - AppServiceProvider.php versus app.php
Asked Answered
A

2

8

Where do I specify my bindings exactly? It seems I can do it in either of these files.

config/app.php Inside of 'providers' =>

app/Providers/AppServiceProvider.php Inside of register()

Abbacy answered 21/5, 2015 at 13:56 Comment(2)
Totally valid question but thanks for the close voteAbbacy
You register bindings in a service provider, and you load service providers via config/app.php.Sized
G
3

If your bindings are not related to App, then I would create a new ServiceProvider class where I overwrite the register method with my new binding, then you have to let Laravel know that this class exists registering as a Provider in your config/app.php providers list, that is:

app/Providers/MyNewClassServiceProvider.php

<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class MyNewClassServiceProvider extends ServiceProvider {
 public function register()
 {
    $this->app->bind(
        'App\Repository\MyNewClassInterface',
        'App\Repository\MyNewClassRepository'
    );
 }
}

config/app.php

'providers' => [
// Other Service Providers

'App\Providers\MyNewClassServiceProvider',
],
Germander answered 21/5, 2015 at 15:11 Comment(0)
S
8

The service providers array is loaded via config/app.php. This is the only actual place that providers are registered, and is where you should put Service Providers.

AppServiceProvider is for Laravel-specific services that you've overridden (or actually specified), such as the Illuminate\Contracts\Auth\Registrar, The HTTP/Console Kernels, and anything you wish to override in Laravel. This is a single service provider, that registers container bindings that you specify.

Really, you could load anything you want here, but there's a bunch of ready-to-go service providers in the app/Providers directory for you so you don't have to go and make one yourself.

Shanna answered 21/5, 2015 at 15:28 Comment(0)
G
3

If your bindings are not related to App, then I would create a new ServiceProvider class where I overwrite the register method with my new binding, then you have to let Laravel know that this class exists registering as a Provider in your config/app.php providers list, that is:

app/Providers/MyNewClassServiceProvider.php

<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class MyNewClassServiceProvider extends ServiceProvider {
 public function register()
 {
    $this->app->bind(
        'App\Repository\MyNewClassInterface',
        'App\Repository\MyNewClassRepository'
    );
 }
}

config/app.php

'providers' => [
// Other Service Providers

'App\Providers\MyNewClassServiceProvider',
],
Germander answered 21/5, 2015 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.