依赖注入在Laravel 5.2中的迁移文件中不起作用

Yah*_*din 6 laravel laravel-5 laravel-5.2

我正在尝试将单身人士用于特定班级.

我在"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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将此类包含在我的迁移文件中,如下所示:

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我执行时,php artisan migrate我得到以下错误,表明依赖注入不起作用.

 [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   
Run Code Online (Sandbox Code Playgroud)

请注意,我已经使用过这个类是其他地方(例如在路由文件中)没有问题.似乎仅在迁移文件中存在此问题!

Yah*_*din 6

正如@lagbox所提到的,IoC容器似乎无法解析迁移文件.

但是仍然可以使用app make方法解决它们,如下所示:

<?php

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

class CreateUsersTable extends Migration
{
    private $applicationFormHelper;

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

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

    public function down()
    {
        Schema::drop('users');
    }
}
Run Code Online (Sandbox Code Playgroud)