mardi 5 juillet 2016

Dependency Injection not working in migration files in Laravel 5.2

I'm trying to use singletons for a specific class.

I did this trivially using the following in the "AppServicePrvider.php":

<?php

namespace App\Providers;

use App\Helpers\ApplicationFormHelper;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {

    }

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

I then included this class in my migration file like so:

<?php

use App\Helpers\ApplicationFormHelper;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    private $applicationFormHelper;

    public function __construct(ApplicationFormHelper $applicationFormHelper)
    {
        $this->applicationFormHelper = $applicationFormHelper;
    }

    public function up()
    {
        //...
    }

    public function down()
    {
        Schema::drop('users');
    }
}

However when I execute php artisan migrate I get the following error, indicating that dependency injection is not working.

 [Symfony\Component\Debug\Exception\FatalThrowableError]                                                             
  Type error: Argument 1 passed to CreateUsersTable::__construct() must be an instance of App\Helpers\ApplicationFor  
  mHelper, none given, called in /home/vagrant/saroia/vendor/laravel/framework/src/Illuminate/Database/Migrations/Mi  
  grator.php on line 335   

Note that I have used this class is other places (e.g. in the routes file) with no problem. It seems to be only in the migrations file that this issue exists!

Please help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire