我试图使用单身人士为特定的类。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();
});
}
}
我遂把这个类在我的移民文件,像这样:
<?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');
}
}
然而,当我执行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
请注意,我已经使用这个类是其他地方(如在路径文件中)没有问题。似乎只有在迁移文件中存在此问题!
是的,我需要的是单身。那么如何执行依赖注入呢? –