Laravel - bindings file for repositories

- 1 answer

Ad

So I have an App\bindings.php file that I have added to my composer.json file as so:

"autoload": {
    "files": [
        "app/bindings.php"
    ]
},

In this file I am trying to set up bindings for my repositories like so:

<?php 

function getRepoBinding($id)
{
    $repo = "{$id}Repository";

    $clientName = strtoupper(config('client.name'));
    $implementation = config('app.repo_implementation', 'Eloquent');
    $clientOverride = "App\Overrides\\{$clientName}\Repositories\\{$implementation}\\{$repo}";
    $repo = class_exists($clientOverride) ? $clientOverride : "App\Repositories\\{$implementation}\\{$repo}";
    return $repo;
}
// Repository Interface Bindings
dd(getRepoBinding('Contribution'));
App::bind('ContributionIneterface', getRepoBinding('Contribution'));

However, i run a composer dump-auto and try to run my application and I get the following error:

Fatal error: Uncaught Error: Call to a member function make() on null in /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:54 
Stack trace: #0 /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(158): app('config') 
#1 /home/vagrant/Code/famsapi/app/bindings.php(9): config('client.name') 
#2 /home/vagrant/Code/famsapi/app/bindings.php(16): App\getRepoBinding('Contribution') 
#3 /home/vagrant/Code/famsapi/vendor/composer/autoload_real.php(55): require('/home/vagrant/C...') 
#4 /home/vagrant/Code/famsapi/vendor/composer/autoload_real.php(45): composerRequire03fe235c8b3156f0c5fcebbc0d696734('90f93262f3a0ac8...', '/home/vagrant/C...') 
#5 /home/vagrant/Code/famsapi/vendor/autoload.php(7): ComposerAutoloaderInit03fe235c8b3156f0c5fcebbc0d696734::getLoader() 
#6 /home/vagrant/Code/famsapi/bootstrap/autoload.php(17): require('/home/vagrant/C...') 
#7 /home/vagrant/Code/famsapi/public/index.php(22): require('/home/vagrant/C...') 
#8 {main} thrown in /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 54

It seems like it is having with the global config helper method...but im not sure how to fix that. Better yet, if you have an idea of how I can do this another way I am all ears.

Ad

Answer

Ad

It is because you are loading that file before the application starts.

Use it inside your AppServiceProvider

Ad
source: stackoverflow.com
Ad